/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only : accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.businessservice.yysl.controller;


import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.soil_humidity;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.Entitess;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.FineForecast;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.MsgMediumSmallScale;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.MsgSmallScaleInfo;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.potential_points;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.warn_moni_info;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.Warning;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.yysl.service.IBasicInfoService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.weblib.GridAnalysis;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/skgl")
public class BasicInfoController {
    private  final String operatingSystem;

    @Autowired
    public BasicInfoController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    //MongoService1 mongoService = new MongoService1();
    FileRequestService mongoService = new FileRequestService();
    ProcessRequestController prco = new ProcessRequestController();
    @Resource
    private IBasicInfoService basicInfoService;

    @Resource
    private ITransformService transformService;


    /****
     * 验证用户  验证登录名和密码
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/CheckUser")
    @ResponseBody
    public Object CheckUser(HttpServletRequest request, Model model) {
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        Object result = basicInfoService.CheckLogin(userName, passWord);
        return result;
    }

    /***
     * 查询欢迎词信息
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetReservoirWel")
    @ResponseBody
    public Object GetReservoirWel(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetReservoirWel();
        return list;
    }

    /***
     * 查询最新的实况信息
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetNewestMsgScale")
    @ResponseBody
    public Object GetNewestMsgScale(HttpServletRequest request, Model model) {
        String stationID = request.getParameter("stationID");
        Object list = basicInfoService.GetNewestMsgScale(stationID);
        return list;
    }

    /***
     * 查询最新的QPF数据   ntimes   030 / 060
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetNewestQPF")
    @ResponseBody
    public Object GetNewestQPF(HttpServletRequest request, Model model) {
        String ntimes = request.getParameter("ntimes");
        String longitude = request.getParameter("longitude");
        String latitude = request.getParameter("latitude");
        Object list = basicInfoService.GetNewestQPF(request, ntimes, longitude, latitude);
        return list;
    }

    /***
     * 短临降水格点
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetGridData")
    @ResponseBody
    public Object GetGridData(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetGridData(request);
        return list;
    }


    /****
     * 获取七天城镇预报  两个地方用到
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetSevenForecast")
    @ResponseBody
    public Object GetSevenForecast(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetSevenForecast(request);
        return list;
    }

    /***
     * 获取预警信号  当天
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWarnSignalInfo")
    @ResponseBody
    public Object GetWarnSignalInfo(HttpServletRequest request, Model model) {
        List<Object> rltList = new ArrayList<>();
        Object list = basicInfoService.GetWarnSignalInfo();
        rltList.add(list);
        String stationname = request.getParameter("stationname");//站点名称
        if (!StringUtil.IsNullOrEmpty(stationname) && stationname.endsWith("水库")) {
            stationname.substring(0, stationname.length() - 2);
            Object list1 = basicInfoService.GetWaterWarnMoniInfo(stationname);
            rltList.add(list1);
        }
        Object list2 = basicInfoService.GetRiverWarnMoniInfo();
        rltList.add(list2);
        return rltList;
    }

    /***
     * 通知信息查询 当天
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetReservoirNotice")
    @ResponseBody
    public Object GetReservoirNotice(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetReservoirNotice();
        return list;
    }

    /***
     * 当天山洪预警查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetSlWarningToday")
    @ResponseBody
    public Object GetSlWarningToday(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetSlWarningToday(request);
        return list;
    }

    /***
     * 最新一条山洪预警查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetSlWarningNewest")
    @ResponseBody
    public Object GetSlWarningNewest(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetSlWarningNewest(request);
        return list;
    }

    /***
     * 最新一条地质灾害预警查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetDZWarningNewest")
    @ResponseBody
    public Object GetDZWarningNewest(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetDZWarningNewest(request);
        return list;
    }

    /***
     * 降雨监控查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWarnMoniInfo")
    @ResponseBody
    public Object GetWarnMoniInfo(HttpServletRequest request, Model model) {
        String stationid = request.getParameter("stationid");//关联的最近的站点
        Object list = basicInfoService.GetWarnMoniInfo(stationid);
        return list;
    }

    /***
     * 超警戒水位查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWaterWarnMoniInfo")
    @ResponseBody
    public Object GetWaterWarnMoniInfo(HttpServletRequest request, Model model) {
        String stationname = request.getParameter("stationname");//站点名称
        if (!StringUtil.IsNullOrEmpty(stationname) && stationname.endsWith("水库"))
            stationname.substring(0, stationname.length() - 2);
        Object list = basicInfoService.GetWaterWarnMoniInfo(stationname);
        return list;
    }

    /***
     * 河道水位监控
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetRiverWarnMoniInfo")
    @ResponseBody
    public Object GetRiverWarnMoniInfo(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetRiverWarnMoniInfo();
        return list;
    }

    /***
     * 获取雷达图  最新十张
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetTenDoppler")
    @ResponseBody
    public Object GetTenDoppler(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetTenDoppler(request);
       return list;
    }

    /****
     * 获取云图   最新十张
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetTenSatelliteNephoram")
    @ResponseBody
    public Object GetTenSatelliteNephoram(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetTenSatelliteNephoram(request);
        return list;
    }

    /****
     * 实况监测  24小时   过去30天
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetMsgSmallScale")
    @ResponseBody
    public Object GetMsgSmallScale(HttpServletRequest request, Model model) {
        String stationId = request.getParameter("stationId");
        DateTime currentTime = DateTime.now();
        DateTime strDate1 = currentTime.AddDays(-1); // 开始时间
        DateTime strDate2 = currentTime; // 开始时间
        Object list = basicInfoService.GetMsgSmallScale("日均", stationId, strDate1, strDate2);
        strDate1 = currentTime.AddDays(-23); // 开始时间
        strDate2 = currentTime; // 开始时间
        Object list1 = basicInfoService.GetMsgSmallScale("小时", stationId, strDate1, strDate2);
        List<Object> resultList = new ArrayList<>();
        resultList.add(list);
        resultList.add(list1);
        return new ResultObj("查询成功", resultList, true);
    }

    /***
     * 得到1 3 6 12 24 小时图片
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetMsgSmallScaleInfo")
    @ResponseBody
    public Object GetMsgSmallScaleInfGetMsgSmallScaleInfoo(HttpServletRequest request, Model model) throws Exception {
        /*************************分布图****************************/
        DateTime time = DateTime.now();
        String rainType = request.getParameter("rainType");
        if (rainType == null) {
            return new ResultObj("查询失敗", "无数据请求", false);
        }
        String drainagearea = request.getParameter("drainagearea");
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Rain\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Rain/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String s = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = s.substring(11, 13);
        String datechar = "";
        if (time.GetMinute() > 10) {
            datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";
        } else {
            datechar = time.AddHours(-1).toDateTimeString("yyyy-MM-dd") + " " + time.AddHours(-1).GetHour() + ":" + "00" + ":" + "00";
            time = time.AddHours(-1);
        }
        String[] types = {"色斑图", "点状图"};
        String pic = "";
        for (int i = 0; i < types.length; i++) {
            String picpath = "";
            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + time.GetHour() + "_"
                    + rainType + "_" + types[i] + "_" + drainagearea + ".jpg";
            String path = request.getContextPath();
            String servicePath = urlpath + fileName;// 服务器文件
            String basePath = DbConfig.IP + path + "/Temp/Rain/";
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
                pic = pic + picpath + "*";
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("datetime", datechar);
                map.put("sx", rainType);
                map.put("drainagearea", drainagearea);
                map.put("collectionName", "sk_jpg_sl_file");
                map.put("type", types[i]);
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data==null||new String(data).equals("")) {
                    if (time.GetMinute() > 10) {
                        datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";
                    } else {
                        datechar = time.AddHours(-2).toDateTimeString("yyyy-MM-dd") + " " + time.AddHours(-2).GetHour() + ":" + "00" + ":" + "00";
                        time = time.AddHours(-2);
                    }
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    map1.put("datetime", datechar);
                    map1.put("sx", rainType);
                    map1.put("drainagearea", drainagearea);
                    map1.put("collectionName", "sk_jpg_sl_file");
                    map1.put("type", types[i]);
                    map1.put("advCode", DbConfig.advCode);
                    byte[] data2 = mongoService.selectData(map1);
                    if (data!=null) {
                        FileUtil.bytesToFile(data2, servicePath);
                        picpath = basePath + fileName;
                        pic = pic + picpath + "*";
                    }
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                    pic = pic + picpath + "*";
                }
            }
        }
        if (!pic.equals("")){
            pic = pic.substring(0, pic.length() - 1);
        }

        /*************************统计信息****************************/
        Object description = basicInfoService.GetMsgSmallScaleTj(rainType, time);
        /*******************降雨量级（统计信息已有）*********************/
        List<staResult> rainList = basicInfoService.GetMsgSmallScaleJyLevel(rainType, time);
        /***************************面雨量***************************/
        List<SurfaceRainResult> resultList = (List<SurfaceRainResult>) getSRainfall(rainType, time);
        /*************************站点排序****************************/
        List<MsgMediumSmallScale> staList = basicInfoService.GetMsgSmallScaleList(rainType, time);
        List<MsgSmallScaleInfo> infos = new ArrayList<>();
        MsgSmallScaleInfo info = new MsgSmallScaleInfo();
        info.setPicpath(pic);
        info.setDescription(description.toString());
        info.setLevel(resultList);
        info.setStalist(staList);
        info.setRainList(rainList);
        infos.add(info);

        return new ResultObj("查询成功", infos, true);
    }


    /***
     * 三维得到1 3 6 12 24 小时图片
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/Get3dMsgSmallScaleInfo")
    @ResponseBody
    public Object Get3dMsgSmallScaleInfo(HttpServletRequest request, Model model) throws Exception {
        List<MsgInfo> infos = new ArrayList<>();
        DateTime time = DateTime.now();
        String[] rainTypes = new String[]{"1", "3", "6", "12", "24"};
        String drainagearea = request.getParameter("drainagearea");
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\3dRain\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/3dRain/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String s = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = s.substring(11, 13);
        String datechar = "";
        if (time.GetMinute() > 20) {
            datechar = time.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";
        } else {
            datechar = time.AddHours(-1).toDateTimeString("yyyy-MM-dd") + " " + time.AddHours(-1).GetHour() + ":" + "00" + ":" + "00";
        }

        String pic = "";
        for (int i = 0; i < rainTypes.length; i++) {
            String picpath = "";
            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + time.GetHour() + "_"
                    + rainTypes[i] + drainagearea + ".png";
            String path = request.getContextPath();
            String servicePath = urlpath + fileName;// 服务器文件
            String basePath = DbConfig.IP + path + "/Temp/3dRain/";
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("datetime", datechar);
                map.put("sx", rainTypes[i]);
                map.put("drainagearea", drainagearea);
                map.put("collectionName", "sk_png_sl_file");
                map.put("type", "色斑图");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null || new String(data).equals("")) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            MsgInfo info = new MsgInfo();
            info.setDatechar(datechar);
            info.setPath(picpath);
            info.setNtimes(rainTypes[i]);
            infos.add(info);
        }

        return new ResultObj("查询成功", infos, true);
    }

    public class MsgInfo {
        private String datechar;
        private String path;
        private String ntimes;

        public String getDatechar() {
            return datechar;
        }

        public void setDatechar(String datechar) {
            this.datechar = datechar;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public String getNtimes() {
            return ntimes;
        }

        public void setNtimes(String ntimes) {
            this.ntimes = ntimes;
        }
    }


    /***
     * 精细化预报  七张图
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetForecastPicInfo")
    @ResponseBody
    public Object GetForecastPicInfo(HttpServletRequest request, Model model) throws ParseException, ParseException {
        List<ForecastRain> rains = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
       // String[] types = new String[]{"003", "006", "009", "012", "015", "018","021","024"};
        String[] types = new String[]{"012", "024", "036", "048", "060", "072","084","096"};
        String drainagearea = request.getParameter("drainagearea");
        String newestDate = basicInfoService.GetForecastTimeInfo();
        String strtime = "20" + newestDate.substring(0, 2) + "-" + newestDate.substring(2, 4) + "-" + newestDate.substring(4, 6) + " " + newestDate.substring(6, 8) + ":00:00";

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = sdf1.parse(strtime);
        String hours = getDatePoor(time.toDate(), d1);


        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/ForecastRain/";
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\ForecastRain\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/ForecastRain/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String datechar = "20" + newestDate.substring(0, 2) + "-" + newestDate.substring(2, 4) + "-" + newestDate.substring(4, 6);
        String timechar = newestDate.substring(6, 8);
        String forecast = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).toDateTimeString("yyyyMMddHH");
        for (String type : types) {
            ForecastRain r = new ForecastRain();
            String fileName = datechar + "_" + timechar + "_" + type + drainagearea + ".png";
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器

                picpath = "/Temp/ForecastRain/" + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                //map.put("datetime", datechar);
                map.put("datechar", datechar);
                map.put("timechar", timechar);
                //map.put("sx", type);
                map.put("ntimes", type);
                map.put("type","降水量");
               // map.put("drainagearea", drainagearea);
                map.put("collectionName", "yb_rain_jpg_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null || new String(data).equals("")) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = "/Temp/ForecastRain/" + fileName;
                }
            }
            r.setPath(picpath);
            String starttime = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).toDateTimeString("MM-dd HH") + "时";
            String endtime = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).AddHours(Integer.parseInt(type)).toDateTimeString("MM-dd HH") + "时";
            r.setTime(starttime + " - " + endtime);
            rains.add(r);
        }
        return new ResultObj("查询成功", rains, true);
    }


    /***
     * 三维精细化预报  一张图
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/Get3dForecastPicInfo")
    @ResponseBody
    public Object Get3dForecastPicInfo(HttpServletRequest request, Model model) throws ParseException {
        List<ForecastRain> rains = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        //String[] types = new String[]{"003", "006", "012", "024", "048", "072"};
        String[] types = new String[]{"012", "024", "036", "048", "060", "072"};
        String drainagearea = request.getParameter("drainagearea");
        String newestDate = basicInfoService.GetForecastTimeInfo();
        String strtime = "20" + newestDate.substring(0, 2) + "-" + newestDate.substring(2, 4) + "-" + newestDate.substring(4, 6) + " " + newestDate.substring(6, 8) + ":00:00";

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = sdf1.parse(strtime);
        String hours = getDatePoor(time.toDate(), d1);


        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/3dForecastRain/";
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\3dForecastRain\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/3dForecastRain/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String datechar = "20" + newestDate.substring(0, 2) + "-" + newestDate.substring(2, 4) + "-" + newestDate.substring(4, 6);
        String timechar = newestDate.substring(6, 8);
        String forecast = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).toDateTimeString("yyyyMMddHH");
        for (String type : types) {
            ForecastRain r = new ForecastRain();
            String fileName = datechar + "_" + timechar + "_" + type + drainagearea + ".png";
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                //map.put("datetime", datechar);
                map.put("datechar", datechar);
                map.put("timechar", timechar);
                //map.put("sx", type);
                map.put("ntimes", type);
                map.put("type","降水量");
                // map.put("drainagearea", drainagearea);
                map.put("collectionName", "yb_rain_jpg_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null || new String(data).equals("")) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            r.setPath(picpath);
            String starttime = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).toDateTimeString("MM-dd HH") + "时";
            String endtime = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).AddHours(Integer.parseInt(type)).toDateTimeString("MM-dd HH") + "时";
            r.setTime(starttime + " - " + endtime);
            rains.add(r);
        }
        return new ResultObj("查询成功", rains, true);
    }


    public static String getDatePoor(Date endDate, Date nowDate) {

        long nd = 1000 * 24 * 60 * 60;//每天毫秒数

        long nh = 1000 * 60 * 60;//每小时毫秒数

        long nm = 1000 * 60;//每分钟毫秒数

        long diff = endDate.getTime() - nowDate.getTime(); // 获得两个时间的毫秒时间差异

        long day = diff / nd;   // 计算差多少天

        long hour = diff % nd / nh; // 计算差多少小时

        long min = diff % nd % nh / nm;  // 计算差多少分钟

        return day * 24 + hour + "";

    }

    /***
     * 预报雨量结果
     */
    public class ForecastRain {
        private String path;
        private String time;

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }
    }

    /***
     * 河道信息（列表+时序图）
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWaterListChart")
    @ResponseBody
    public Object GetWaterListChart(HttpServletRequest request, Model model) {
        String location = request.getParameter("location");
        if (StringUtil.IsNullOrEmpty(location))
            location = "城步县";
        Object list = basicInfoService.GetWaterListChart(location);
        return list;
    }

    /***
     * 水情
     */
    @RequestMapping("/waterQuery")
    @ResponseBody
    public Object waterQuery(HttpServletRequest request, Model model) {
        Date startDate = DateTime.now().AddHours(-1).toDate();
        Date endDate = DateTime.now().toDate();
        Object resultList = basicInfoService.waterQuery(startDate, endDate);
        return resultList;
    }

    /****
     * 水库信息  实况数据
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetReservoirWaterInfo")
    @ResponseBody
    public Object GetReservoirWaterInfo(HttpServletRequest request, Model model) {
        String county = request.getParameter("county");
        if (StringUtil.IsNullOrEmpty(county))
            county = DbConfig.CITY;
        Object list = basicInfoService.GetReservoirWaterInfo(county);
        return list;
    }

    /***
     * 水库信息查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetReservoirInfo")
    @ResponseBody
    public Object GetReservoirInfo(HttpServletRequest request, Model model) {
        String reservoirid = request.getParameter("reservoirid");
        if (StringUtil.IsNullOrEmpty(reservoirid))
            return new ResultObj("查询失败", "水库ID为空!", false);
        Object list = basicInfoService.GetReservoirInfo(request, reservoirid);
        return list;
    }

    /***
     * 办公文件查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetReservoirFiles")
    @ResponseBody
    public Object GetReservoirFiles(HttpServletRequest request, Model model) {
        String reservoirid = request.getParameter("reservoirid");
        if (StringUtil.IsNullOrEmpty(reservoirid))
            return new ResultObj("查询失败", "水库ID为空!", false);
        Object list = basicInfoService.GetReservoirFiles(request, reservoirid);
        return list;
    }

    /***
     * 土壤湿度
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/soilChart")
    @ResponseBody
    public Object soilChart(HttpServletRequest request, Model model) throws ParseException {
        DateTime currentTime = DateTime.now();
        String startDate = currentTime.AddHours(-23).toDateTimeString("yyyy-MM-dd HH");
        String endDate = currentTime.toDateTimeString("yyyy-MM-dd HH");
        String stationId = request.getParameter("stationId");
        String stationname = request.getParameter("stationname");
        String type = request.getParameter("type");
        if (StringUtil.IsNullOrEmpty(stationId))
            stationId = DbConfig.STATIONID;//常德站点代替
        String level = request.getParameter("level");
        if (StringUtil.IsNullOrEmpty(level))
            level = "10";
        List<soil_humidity> resultList = basicInfoService.soilChart(stationId, startDate, endDate, level);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        Map<String, List<Double>> stationValMap1 = new HashMap<String, List<Double>>();
        for (int i = 0; i < resultList.size(); i++) {
            level = String.valueOf(resultList.get(i).getLevel());
            if (level.equals(String.valueOf(resultList.get(0).getLevel()))) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd HH");
                String time = simpleDateFormat.format(resultList.get(i).getObservetime());
                hours.add(time);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                times.add(simpleDateFormat1.format(resultList.get(i).getObservetime()));
            }
            List<Double> values1 = new ArrayList<Double>();
            if (!stationValMap1.keySet().contains(level)) {
                if (resultList.get(i).getRelhumidity() != 0 && resultList.get(i).getRelhumidity() != -65535) {
                    values1.add(resultList.get(i).getRelhumidity());
                    stationValMap1.put(level, values1);
                } else {
                    values1.add(0.0);
                }

            } else {
                if (resultList.get(i).getRelhumidity() != 0 && resultList.get(i).getRelhumidity() != -65535) {
                    stationValMap1.get(level).add(resultList.get(i).getRelhumidity());
                }
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        result.add(times);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        return new ResultObj("查询成功", result, true);
    }

    /***
     * 干旱监测
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/droughtChart")
    @ResponseBody
    public Object droughtChart(HttpServletRequest request, Model model) throws ParseException {
        DateTime currentTime = DateTime.now();
        String startDate = currentTime.AddMonths(-1).toDateString();
        String endDate = currentTime.toDateString();
        String stationname = request.getParameter("stationId");
        if (StringUtil.IsNullOrEmpty(stationname))
            stationname = DbConfig.STATIONID;
        List<drought> resultList = basicInfoService.droughtChart(startDate, endDate, stationname);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        List<Float> values1 = new ArrayList<Float>();
        Map<String, List<Float>> stationValMap1 = new HashMap<String, List<Float>>();
        for (int i = 0; i < resultList.size(); i++) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd");
            String time = simpleDateFormat.format(resultList.get(i).getObservationdate());
            hours.add(time);
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            times.add(simpleDateFormat1.format(resultList.get(i).getObservationdate()));
            values1.add(resultList.get(i).getDryobservationvalue());
        }
        stationValMap1.put(stationname, values1);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        result.add(times);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        return new ResultObj("查询成功", result, true);
    }


    /* 得到灾点查询 */
    @RequestMapping("/getDPoint")
    @ResponseBody
    public Object getDPoint(HttpServletRequest request, Model model) throws Exception {
        potential_points selectKey = new potential_points();// 查询类
        String countys = request.getParameter("countys");//
        String searchParams = request.getParameter("searchParams");//
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String type = request.getParameter("type");
        selectKey.setCity(countys);
        selectKey.setPp_name(searchParams);
        selectKey.setLon(lon);
        selectKey.setLat(lat);
        Object resultList = basicInfoService.getDPoint(selectKey, type);
        return resultList;
    }

    /***
     * 定位到流域
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/getRiverBasin")
    @ResponseBody
    public Object getRiverBasin(HttpServletRequest request, Model model) throws Exception {
        Object resultList = basicInfoService.getRiverBasin();
        return resultList;
    }


    /* QPF查询 */
    @RequestMapping("/QPFquery")
    @ResponseBody
    public Object getQPFForecast(HttpServletRequest request, Model model) throws Exception {
        String longitude = request.getParameter("lon");// 经度
        String latitude = request.getParameter("lat");// 经度
        if (longitude == null || latitude == null) {
            return new ResultObj("查询失敗", "经纬度未知", false);
        }
        String strType = request.getParameter("ntimes");// 类型
        DmMapPoint dt = transformService.LonLatConvertToLambert(Double.parseDouble(longitude), Double.parseDouble(latitude));
        String temp = "";
        if (!strType.contains("12")) {
            String ntimes = "060";
            List<qpe_qpf> resultList = basicInfoService.getQPFForecast(ntimes);
            String gridpath = "";
            if (resultList != null && resultList.size() > 0) {
                String xValue = "[";
                String yValue = "[";
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
                SimpleDateFormat format1 = new SimpleDateFormat("HH:mm");
                for (int i = resultList.size() - 1; i >= 0; i--) {
                    String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\QPF\\";// 临时文件目录
                    FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                    FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                    String fileName = format.format(resultList.get(i).getDatechar()) + "_" + strType + ".grid";
                    String servicePath = urlpath + fileName;// 服务器文件
                    File serviceFile = new File(servicePath);// 服务器文件
                    if (serviceFile.exists()) {// 把文件上传到服务器
                        gridpath = "Temp\\QPF\\" + fileName;
                    } else {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("datechar", format.format(resultList.get(i).getDatechar()));
                        map.put("type", "QPF");
                        map.put("ntimes", ntimes);
                        map.put("collectionName", "qpf_grid_file");
                        byte[] data = mongoService.selectData(map);
                        if (new String(data).equals("")) {
                            gridpath = "";
                        } else {
                            FileUtil.bytesToFile(data, servicePath);
                            gridpath = "Temp\\QPF\\" + fileName;
                        }
                    }
                    if (gridpath != "") {
                        GridAnalysis grd = new GridAnalysis();
                        grd.openFile(servicePath);
                        double value = grd.getElevationAt(dt.x, dt.y);
                        if (value == -99999) value = 0;
                        xValue += "'" + format1.format(resultList.get(i).getDatechar()) + "',";
                        yValue += value + ",";
                    }
                }
                xValue = xValue.substring(0, xValue.length() - 1) + "]";
                yValue = yValue.substring(0, yValue.length() - 1) + "]";
                yValue = "[{name:'雨量',data:" + yValue + "}]";
                temp = xValue + "|" + yValue;
            } else {
                temp = "[]";
            }

        } else {
            try {
                DateTime time = DateTime.now();
                String[] sxlist = new String[12];
                String fileName;
                String sc = "";
                int startNtimes = time.GetHour();
                DateTime dateTime = time;
                for (int i = 0; i < sxlist.length; i++) {
                    int a = startNtimes + (i + 1);
                    if (a != 24) {
                        sxlist[i] = String.format("%03d", a % 24);
                    } else {
                        sxlist[i] = String.format("%03d", a);
                    }
                }
                if (time.GetHour() >= 0 && time.GetHour() < 8) {
                    dateTime = dateTime.AddDays(-1);
                    sc = "20";
                } else if (time.GetHour() >= 8 && time.GetHour() < 20) {
                    sc = "08";//获取当天的08时预报
                } else {
                    sc = "20";//获取当天的20时预报
                }
                if (sxlist != null && sxlist.length > 0) {
                    String gridpath = "";
                    String xValue = "[";
                    String yValue = "[";
                    for (int i = 0; i < sxlist.length; i++) {
                        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\精细化预报\\";// 临时文件目录
                        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                        fileName = dateTime.toDateString() + sxlist[i] + "_" + strType + ".grid";
                        String servicePath = urlpath + fileName;// 服务器文件
                        File serviceFile = new File(servicePath);// 服务器文件
                        if (serviceFile.exists()) {// 把文件上传到服务器
                            gridpath = "Temp\\精细化预报\\" + fileName;
                        } else {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("datechar", dateTime.toDateString());
                            map.put("type", "R");
                            map.put("ntimes", sxlist[i]);
                            map.put("forecasttype", "1");
                            map.put("timechar", sc);
                            map.put("collectionName", "ybzz_final_grid");
                            map.put("advCode", DbConfig.advCode);
                            byte[] data = mongoService.selectData(map);
                            if (new String(data).equals("")) {
                                gridpath = "";
                            } else {
                                FileUtil.bytesToFile(data, servicePath);
                                gridpath = "Temp\\精细化预报\\" + fileName;
                            }
                        }
                        if (gridpath != "") {
                            GridAnalysis grid = new GridAnalysis();
                            grid.openFile(servicePath);
                            double value = grid.getElevationAt(dt.x, dt.y);
                            if (value == -99999) value = 0;
                            xValue += "'" + sxlist[i].substring(1, 3) + ":00" + "',";
                            yValue += value + ",";
                        }
                    }
                    xValue = xValue.substring(0, xValue.length() - 1) + "]";
                    yValue = yValue.substring(0, yValue.length() - 1) + "]";
                    yValue = "[{name:'雨量',data:" + yValue + "}]";
                    temp = xValue + "|" + yValue;
                } else {
                    temp = "[]";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ResultObj("查询成功", temp, true);
    }


    /***
     * 精细化预报降水（1小时、3小时、12小时） ???
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetForecastInfo")
    @ResponseBody
    public Object GetForecastInfo(HttpServletRequest request, Model model) {
        String forecasttype = request.getParameter("forecasttype");// 1 3 12
        if (forecasttype == null) {
            return new ResultObj("查询失败", "参数为空", false);
        }
        String rainType = "R";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\ForecastRain\\";// 临时文件目录
        List<String> picpaths = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String datechar = time.toDateTimeString("yyyy-MM-dd");
        String timechar = (time.GetHour() >= 8 && time.GetHour() < 20) ? "08" : "20";
        List<String> ntimes = new ArrayList<>();
        if (forecasttype.equals("1")) {
            for (DateTime ti = time.AddDays(-1); ti.before(time); ti.AddHours(1))
                ntimes.add(String.valueOf(ti.GetHour()));
        } else if (forecasttype.equals("3")) {
            for (DateTime ti = time.AddDays(-3); ti.before(time); ti.AddHours(3))
                ntimes.add(String.valueOf(ti.GetHour()));
        } else if (forecasttype.equals("12")) {
            for (int i = 1; i <= 14; i++)
                ntimes.add("0" + 12 * i);
        }
        for (String ntime : ntimes) {
            String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + timechar + "_"
                    + ntimes + "_" + rainType + ".png";
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = "Temp\\ForecastRain\\" + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("datechar", datechar);
                map.put("timechar", timechar);
                map.put("ntimes", ntime);
                map.put("forecasttype", forecasttype);
                map.put("type", rainType);
                map.put("collectionName", "ybzz_final_grid");
                byte[] data = mongoService.selectData(map);
                if (new String(data).equals("")) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = "Temp\\ForecastRain\\" + fileName;
                }
            }
            picpaths.add(picpath);
        }
        return new ResultObj("查询成功", picpaths, true);
    }

    /***
     * 乡镇预报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/ChenZhenYuBao")
    @ResponseBody
    public Object getCityFcst(HttpServletRequest request, Model model) {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        DateTime currentTime = DateTime.now();
        String time = currentTime.toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
        String sc = (currentTime.GetHour() >= 8 && currentTime.GetHour() < 20 ? "08" : "20"); // 预报时次
        if (currentTime.GetHour() >= 8 && currentTime.GetHour() <= 20)
            sc = "08";
        else if (currentTime.GetHour() < 8 && currentTime.GetHour() >= 0) {
            time = currentTime.AddDays(-1).toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
            sc = "20";
        } else sc = "20";
        String sx = "24"; // 时效
        String cityId = request.getParameter("cityId");// 城市
        String county = request.getParameter("county");// 区县
        if (StringUtil.IsNullOrEmpty(county))
            county = DbConfig.CITY;
        String strStationID = "";
        String strCountyName = "";
        int nTimes;
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {
            nTimes = Integer.parseInt(sx);
            if (!(cityId == null) && !cityId.equals("")) {
                selectKey.setStationID(cityId);// 站点号
            }
            selectKey.setNTimes(nTimes);
            selectKey.setTimeChar(sc);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
            List<TownshipForecast> fcstList = basicInfoService.getTownshipFcst(selectKey, county);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i += 2) {
                strStationID = fcstList.get(i).getStationID();
                strCountyName = fcstList.get(i).getStationName();
                if (strCountyName.contains("乡")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                }
                if (strCountyName.contains("镇")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                }
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindD().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindD().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS())));
                String windS12 = String.valueOf(fcstList.get(i).getWindS());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().toString().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().toString().trim()+"转"+fcstList.get(i+1).getWeather1().toString().trim();
                }
                double maxTemp = fcstList.get(i + 1).getMaxTemp();
                double minTemp = fcstList.get(i + 1).getMinTemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1() == null ? "多云" : fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1() == null ? "多云" : fcstList.get(i).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setDatechar(DateTime.parseDate(time).toDate());
                fcstInfo.setTimechar(sc);
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                fcstInfo.setWeather1(wcd.GetWeatherTq(fcstList.get(i).getWeather1().trim()));
                fcstInfo.setWeather2(wcd.GetWeatherTq(fcstList.get(i+1).getWeather1().trim()));
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", resultList, true);
    }

    /***
     * 获取雷达图  最新一张
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetNewestDoppler")
    @ResponseBody
    public Object GetNewestDoppler(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetNewestDoppler(request);
        return list;
    }

    /****
     * 获取云图   最新一张
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetNewestSatelliteNephoram")
    @ResponseBody
    public Object GetNewestSatelliteNephoram(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetNewestSatelliteNephoram(request);
        return list;
    }

    /***
     * 雨量
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/rainQuery")
    @ResponseBody
    public Object rainQuery(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = null;
        Date endDate = null;
        if (StringUtil.IsNullOrEmpty(request.getParameter("startDate")) && StringUtil.IsNullOrEmpty(request.getParameter("endDate"))) {
            startDate = DateTime.parseDateTime(DateTime.now().AddHours(-23).toDateTimeString("yyyy-MM-dd HH:00:00")).toDate();
            endDate = DateTime.parseDateTime(DateTime.now().toDateTimeString("yyyy-MM-dd HH:00:00")).toDate();
        } else {
            startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();
            endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();
        }
        String elemType = request.getParameter("text");
        if (StringUtil.IsNullOrEmpty(elemType))
            elemType = "24小时雨量";
        String[] countys = new String[]{DbConfig.CITY};
        String type = "sum";
        String element = "rain";
        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setCountys(Arrays.asList(countys));
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setType(type);
        List<ActualData> resultlst = new ArrayList<>();
        List<ActualData> resultList = basicInfoService.qxElementQuery(elemQuery);//区域站
        List<ActualData> resultlist1 = basicInfoService.slElementQuery(elemQuery);//雨量站
        for (ActualData data : resultList) {
            ActualData dd = new ActualData();
            data.setType("rain");
            dd = data;
            resultlst.add(dd);
        }
        for (ActualData data : resultlist1) {
            ActualData dd = new ActualData();
            dd = data;
            resultlst.add(dd);
        }
        List<ElemContourSet> contourSet = basicInfoService.getElemContourSet(elemType);
        List<Object> result = new ArrayList<Object>();
        result.add(ClassifyElemByValue(resultlst, contourSet, elemType));
        result.add(contourSet);
        return new ResultObj("查询成功", result, true);
    }

    /***
     * 蒸发量  默认过去10天
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/evaporationQuery")
    @ResponseBody
    public Object evaporationQuery(HttpServletRequest request, Model model) throws ParseException {
        DateTime currentTime = DateTime.now();
        String startDate = currentTime.AddDays(-10).toDateTimeString("yyyy-MM-dd");
        String endDate = currentTime.toDateTimeString("yyyy-MM-dd");
        String stationId = request.getParameter("stationId");
        if (StringUtil.IsNullOrEmpty(stationId))
            stationId = DbConfig.STATIONID;
        List<msgmediumsmallscale> resultList = basicInfoService.evaporationQuery(startDate, endDate, stationId);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        List<Float> values1 = new ArrayList<Float>();
        Map<String, List<Float>> stationValMap1 = new HashMap<String, List<Float>>();
        if (resultList.size() > 0) {
            String stationname = resultList.get(0).getStationname();
            for (int i = 0; i < resultList.size(); i++) {
                hours.add(resultList.get(i).getDatechar());
                times.add(resultList.get(i).getDatechar());
                values1.add(resultList.get(i).getEvaporation());
            }
            stationValMap1.put(stationname, values1);
            ArrayList<Object> result = new ArrayList<Object>();
            result.add(hours);
            result.add(times);
            for (String key : stationValMap1.keySet()) {
                ArrayList<Object> tempArr = new ArrayList<Object>();
                tempArr.add(key);
                tempArr.add(stationValMap1.get(key));
                result.add(tempArr);
            }
            return new ResultObj("查询成功", result, true);
        } else {
            return new ResultObj("查询失败", "", false);
        }


    }

    /***
     * 气温  默认过去24小时
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/tempQuery")
    @ResponseBody
    public Object tempQuery(HttpServletRequest request, Model model) throws ParseException {
        DateTime currentTime = DateTime.now();
        String startDate = currentTime.AddHours(-1).toDateTimeString("yyyy-MM-dd HH");
        String endDate =DateTime.now().toDateTimeString("yyyy-MM-dd HH");
        String stationname = request.getParameter("stationId");
        DateTime cttime = DateTime.now();
        String s = cttime.AddHours(0).toDateTimeString("yyyy-MM-dd HH:mm:ss");
        Object list = tempQuery1(startDate, endDate, stationname, request, s);
        return list;
    }

    public Object tempQuery1(String startDate, String endDate, String stationname, HttpServletRequest request, String s) throws ParseException {

        List<msgmediumsmallscale> resultList = basicInfoService.tempQuery(startDate, endDate, stationname);
        /*************************分布图****************************/
        String picpath = "";
        DateTime cttime = DateTime.now();
        String s2 = cttime.AddHours(-1).toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String rainType = "温度";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\tempPic\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String hour = s.substring(11, 13);
        String hour2 = s2.substring(11, 13);
        String datechar = cttime.toDateTimeString("yyyy-MM-dd") + " " + hour + ":" + "00" + ":" + "00";
        String fileName = cttime.GetYear() + "_" + cttime.GetMonth() + "_" + cttime.GetDay() + "_" + hour + "_"
                + rainType + ".png";
        String fileName2 = cttime.GetYear() + "_" + cttime.GetMonth() + "_" + cttime.GetDay() + "_" + hour2 + "_"
                + rainType + ".png";
        String path = request.getContextPath();
        String servicePath = urlpath + fileName;// 服务器文件
        String basePath = DbConfig.IP + path + "/Temp/tempPic/";
        File serviceFile = new File(servicePath);// 服务器文件
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datechar);
            map.put("type", rainType);
            map.put("collectionName", "sk_temp_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datechar = cttime.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datechar);
                map.put("type", rainType);
                map.put("collectionName", "sk_temp_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    resultList = tempQuery2(datechar);
                    servicePath = urlpath + fileName2;// 服务器文件
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName2;
                }
            }else {
                resultList = tempQuery2(datechar);
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        List<String> county = new ArrayList<String>();
        List<Float> values1 = new ArrayList<Float>();
        Map<String, List<Float>> stationValMap1 = new HashMap<String, List<Float>>();
        for (int i = 0; i < resultList.size(); i++) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd HH");
            String time = simpleDateFormat.format(resultList.get(i).getObservtime());
            hours.add(time);
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            times.add(simpleDateFormat1.format(resultList.get(i).getObservtime()));
            values1.add(resultList.get(i).getDrybulbtemp());
            county.add(resultList.get(i).getCounty());
        }
        stationValMap1.put(stationname, values1);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        result.add(times);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        result.add(picpath);
        result.add(county);
        return new ResultObj("查询成功", result, true);
    }

    public List<msgmediumsmallscale> tempQuery2(String datechar) {
        List<msgmediumsmallscale> resultList = new ArrayList<msgmediumsmallscale>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        columns.add("county");
        columns.add("observtime");
        columns.add("max(drybulbtemp) as drybulbtemp");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (datechar != null) {
            whereCount++;
            strWhere.append(String.format(" observtime='%s'", datechar));
        }
        strWhere.append(String.format("and drybulbtemp!='-65535' and city like '%s%%'", DbConfig.CITY));
        selectRequest.setSort(new String[]{" drybulbtemp asc"});
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = prco.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        // 赋值
        return resultList;
    }

    /****
     * 雨量颜色分级
     * @param actualDatas
     * @param contourSets
     * @param elemType
     * @return
     */
    public List<ActualData> ClassifyElemByValue(List<ActualData> actualDatas, List<ElemContourSet> contourSets,
                                                String elemType) {
        for (ActualData actualData : actualDatas) {
            double value = 0d;
            int color = 16777215;// 白色，默认颜色
            switch (elemType) {
                case "雨量":
                case "1小时雨量":
                case "3小时雨量":
                case "6小时雨量":
                case "12小时雨量":
                case "24小时雨量":
                    value = actualData.getRain();
                    break;
                case "温度":
                    value = actualData.getTemp();
                    break;
                case "风速":
                    value = actualData.getWinds();
                    break;
                case "湿度":
                    value = actualData.getHumid();
                    break;
                case "气压":
                    value = actualData.getPressure();
                default:
                    break;
            }
            for (int i = 0; i < contourSets.size(); i++) {
                ElemContourSet contourSet = contourSets.get(i);
                double level = contourSet.getElementValue();
                if (value >= level) {
                    color = contourSet.getElementColor();
                }
            }
            actualData.setColor(ColorUtil.transWin32ToHtml(color));
        }
        return actualDatas;
    }

    /***
     * 面雨量分析
     * @return
     * @throws Exception
     */
    public Object getSRainfall(String rainType, DateTime time) throws Exception {
        SRainfallSearch selectKey = new SRainfallSearch();// 查询类
        if (rainType == null) {
            return "[]";
        }
        String el = rainType;
        String ntimes = "1";
        if (el.contains("三") || el.contains("3")) {
            ntimes = "3";
        } else if (el.contains("六") || el.contains("6")) {
            ntimes = "6";
        } else if (el.contains("十二") || el.contains("12")) {
            ntimes = "12";
        } else if (el.contains("二十四") || el.contains("24")) {
            ntimes = "24";
        }
        String strDate = time.toDateString()+" "+time.GetHour()+":00:00";// 时间
        selectKey.setStartDate(strDate);
        selectKey.setNtimes(ntimes);
        selectKey.setType("0");//0 实况  1  预报
        selectKey.setAreatype("0");//0 流域  1  行政
        List<area_rain> fcstList = basicInfoService.getSumAreaRain(selectKey);// 雨量
        List<rain_water_shed> rainwaterList = basicInfoService.getRainwater(); // 面雨量流域
        List<SurfaceRainResult> resultList = new ArrayList<SurfaceRainResult>();// 最终结果
        for (rain_water_shed rainwater : rainwaterList) {
            for (area_rain msg : fcstList) {
                if(msg.getAreaname().equals(rainwater.getName())){
                    SurfaceRainResult result = new SurfaceRainResult();
                    result.setName(msg.getAreaname());
                    DecimalFormat df = new DecimalFormat("#.0");
                    result.setSurfacerain(Float.parseFloat(df.format(Float.parseFloat(msg.getRain()))));
                    resultList.add(result);
                }
            }
        }
        return resultList;
    }

    /***
     * 获取QPF  最新十张
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetTenQpf")
    @ResponseBody
    public Object GetTenQpf(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetTenQPF(request);
        return list;
    }

    /***
     * 获取QPF  最新一张  三维使用
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetNewextQpf")
    @ResponseBody
    public Object GetNewextQpf(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetNewextQpf(request);
        return list;
    }

    /****
     * 人员信息  查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetStaffInfo")
    @ResponseBody
    public Object GetStaffInfo(HttpServletRequest request, Model model) {
        String staffid = request.getParameter("staffid");//人员ID
        Object list = basicInfoService.GetStaffInfo(request, staffid);
        return list;
    }

    /****
     * 职能职责  查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetResponsibility")
    @ResponseBody
    public Object GetResponsibility(HttpServletRequest request, Model model) {
        String reservoirid = request.getParameter("reservoirid");//水库ID
        Object list = basicInfoService.GetResponsibility(reservoirid);
        return list;
    }

    /***
     * 一周天气预报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWenziForecast")
    @ResponseBody
    public Object GetWenziForecast(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetWenziForecast(request);
        return list;
    }

    /***
     * 重大天气报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetGreatWeather")
    @ResponseBody
    public Object GetGreatWeather(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetGreatWeather(request);
        return list;
    }

    /***
     * 气象专题报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWeatherSpecial")
    @ResponseBody
    public Object GetWeatherSpecial(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetWeatherSpecial(request);
        return list;
    }

    /***
     * 飞行路线
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetFlypath")
    @ResponseBody
    public Object GetFlypath(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetFlypath(request);
        return list;
    }

    /***
     * 水情  地图展示
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetReWaterInfo")
    @ResponseBody
    public Object GetReWaterInfo(HttpServletRequest request, Model model) {
        Object resultList = basicInfoService.GetReWaterInfo(request);
        return resultList;
    }

    /***
     * 得到水库曲线图
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetReWaterChartsInfo")
    @ResponseBody
    public Object GetReWaterChartsInfo(HttpServletRequest request, Model model) {
        String stcd = request.getParameter("stcd");
        if (StringUtil.IsNullOrEmpty(stcd)) {
            return new ResultObj("查询失败", "ID为空", false);
        }
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        if(startDate == null ) startDate = "";
        if(endDate == null ) endDate = "";
        List<reservoir_water_info> resultList = basicInfoService.GetReWaterChartsInfo(stcd,startDate,endDate);
        List<String> hours = new ArrayList<String>();
        List<Float> values1 = new ArrayList<Float>();
        List<Float> values2 = new ArrayList<Float>();
        List<Float> values3 = new ArrayList<Float>();
        Map<String, List<Float>> stationValMap1 = new HashMap<String, List<Float>>();
        Map<String, List<Float>> stationValMap2 = new HashMap<String, List<Float>>();
        Map<String, List<Float>> stationValMap3 = new HashMap<String, List<Float>>();
        reservoir_water_info sta = new reservoir_water_info();
        if (resultList.size() > 0) {
            String stationname = resultList.get(0).getStationname();
            sta.setStlc(resultList.get(0).getStlc());
            sta.setRvnm(resultList.get(0).getRvnm());
            sta.setWaterlevel(resultList.get(0).getWaterlevel());
            sta.setStorageflow(resultList.get(0).getStorageflow());
            sta.setStationname(resultList.get(0).getStationname());
            sta.setObservtime(resultList.get(0).getObservtime());
            sta.setWaterflow(resultList.get(0).getWaterflow());
            sta.setLimited_waterlv(resultList.get(0).getLimited_waterlv());
            sta.setTotaloutbound(resultList.get(0).getTotaloutbound());
            for (int i = resultList.size() - 1; i >= 0; i--) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH");
                String time = simpleDateFormat.format(resultList.get(i).getObservtime());
                hours.add(time);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                values1.add(Float.parseFloat(resultList.get(i).getWaterlevel().toString()));
                values2.add(resultList.get(i).getStorageflow());
                values3.add(resultList.get(i).getTotaloutbound());
            }
            stationValMap1.put(stationname, values1);
            stationValMap2.put(stationname, values2);
            stationValMap3.put(stationname, values3);
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        for (String key : stationValMap2.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap2.get(key));
            result.add(tempArr);
        }
        for (String key : stationValMap3.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap3.get(key));
            result.add(tempArr);
        }
        result.add(sta);
        result.add(resultList);
        return new ResultObj("查询成功", result, true);
    }

    /**
     * 新闻动态
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetSl_Re")
    @ResponseBody
    public Object GetSl_Re(HttpServletRequest request, Model model) {
        String reservoirid = request.getParameter("reservoirid");
        Object list = basicInfoService.GetSl_Re(request);
        return list;
    }

    /***
     * 城镇预报查询
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */

    @RequestMapping("/CityForecast")
    @ResponseBody
    public Object getCityForecast(HttpServletRequest request, Model model) throws Exception {
        String stationname = request.getParameter("reservoirname");
        List<forecastinfotemp> resultList = new ArrayList<>();
        String strDate = request.getParameter("date");// 时间
        if (strDate == null) {
            return "[]";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateTime dateTime = new DateTime(sdf.parse(strDate));
        String strTime = request.getParameter("sc");// 时次
        String stationID = request.getParameter("stationID");// 类型
        String temp = "";
        if (stationname != null && !stationname.equals("")) {
            forecastinfotemp selectKey = new forecastinfotemp();// 查询类
            selectKey.setDatechar(DateTime.parseDate(strDate).toDate());
            selectKey.setTimechar(strTime);
            selectKey.setStationid(stationID);
            resultList = basicInfoService.getCityForecast(selectKey, "");
            WebCtrlData wcd = new WebCtrlData();
            temp = "[";
            if (resultList != null) {
                String xValue = "[";
                String yValue = "[";
                String yValue1 = "[";
                List<Forecast> listResult = new ArrayList<Forecast>();
                for (forecastinfotemp fit : resultList) {
                    String strforcastSx = fit.getNtimes().toString().trim();
                    DateTime date = dateTime.AddHours(Integer.parseInt(strforcastSx) - 12);

                    SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
                    String week = dateFm.format(date.toDate());

                    String strDateTime = date.GetDay() + "日";
                    String day = date.GetDay() + "日";


                    String strWeather1 = "";
                    strWeather1 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fit.getWeather1().toString())));
                    String strWeather2 = "";
                    strWeather2 = String.format("%02d", Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fit.getWeather2().toString())));


                    String strWeatherDisp = "";
                    if (strWeather1.equals("-65535")) {
                        strWeather1 = "00";
                    }
                    if (strWeather2.equals("-65535")) {
                        strWeather2 = "00";
                    }
                    if (strWeather1.equals(strWeather2))
                        strWeatherDisp = wcd.GetWeatherTq(strWeather1).toString();
                    else
                        strWeatherDisp = wcd.GetWeatherTq(strWeather1).toString() + "</br>转"
                                + wcd.GetWeatherTq(strWeather2).toString();


                    strWeather1 = wcd.GetWeatherTq(strWeather1).toString();
                    strWeather2 = wcd.GetWeatherTq(strWeather2).toString();

                    String weatherCode1 = WebCtrlData.WeatherNameToPicPath(strWeather1);
                    String weatherCode2 = WebCtrlData.WeatherNameToPicPath(strWeather2);

                    String strImgPic1 = "<img height='32px' width='32px' src='../../images/tqyb/weatherDay/" + weatherCode1 + ".gif'>";
                    String strImgPic2 = "<img height='32px' width='32px' src='../../images/tqyb/weatherNight/" + weatherCode2
                            + ".gif'>";

                    String strMinTemp = fit.getMintemp().toString().trim();
                    String strMaxTemp = fit.getMaxtemp().toString().trim();
                    if (strMinTemp.equals("-65535.0") || strMinTemp.equals("65535.0")) {
                        strMinTemp = "";
                    }
                    if (strMaxTemp.equals("-65535.0") || strMaxTemp.equals("65535.0")) {
                        strMaxTemp = "";
                    }
                    String strWindDir1 = "";
                    String strWindDir2 = "";
                    try {
                        strWindDir1 = wcd.GetWeatherFx(String.format("%d", fit.getWindd1())).toString();
                        strWindDir2 = wcd.GetWeatherFx(String.format("%d", fit.getWindd1())).toString();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    if (!strWindDir1.equals(strWindDir2))
                        strWindDir1 = strWindDir1 + "</br>转" + strWindDir2;

                    int minWind = Integer.parseInt(fit.getWind2().toString().substring(0, 1).trim());
                    String minWindS = String.format("%02d", minWind);

                    String maxWindS = "";
                    Float maxwind = fit.getWind1();
                    if(maxwind==-65535)
                        maxWindS = "00";
                    else {
                        int maxWind = Integer.parseInt(fit.getWind1().toString().substring(0, 1).trim());
                        maxWindS = String.format("%02d", maxWind);
                    }

                    String strWindDisp = "";
                    if (minWindS.equals(maxWindS))
                        strWindDisp = wcd
                                .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(minWindS))))
                                .toString();
                    else
                        strWindDisp = wcd
                                .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(minWindS))))
                                .toString() + " 转 "
                                + wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(Double.parseDouble(maxWindS))))
                                .toString();
                    String strRain = fit.getRain().toString().trim();
                    String strHumid = fit.getMaxhumid().toString().trim();
                    if (strRain.equals("-65535.0") || strRain.equals("65535.0")) {
                        strRain = "";
                    }
                    if (strHumid.equals("-65535.0") || strHumid.equals("65535.0")) {
                        strHumid = "";
                    }
                    Forecast f = new Forecast();
                    f.setDateTime(strDateTime);
                    f.setDay(day);
                    f.setWeek(week);
                    f.setWeatherPhenomena(strWeatherDisp);
                    f.setStrWeather1(strWeather1);
                    f.setStrWeather2(strWeather2);
                    f.setMaxTemp(strMaxTemp);
                    f.setMinTemp(strMinTemp);
                    f.setWindD(strWindDir1);
                    f.setWindV(strWindDisp);
                    f.setWeatherPic1(strImgPic1);
                    f.setWeatherPic2(strImgPic2);
                    f.setRain(strRain);
                    f.setMaxhumid(strHumid);
                    listResult.add(f);

                    xValue += "'" + strDateTime + "',";
                    yValue += strMaxTemp + ",";
                    yValue1 += strMinTemp + ",";
                }

                String tableData = "[";
                for (Forecast forecast : listResult) {
                    tableData += "{";
                    tableData += "\"dateTime\":\"" + forecast.getDateTime() + "\",";
                    tableData += "\"maxTemp\":\"" + forecast.getMaxTemp() + "\",";
                    tableData += "\"minTemp\":\"" + forecast.getMinTemp() + "\",";
                    tableData += "\"windD\":\"" + forecast.getWindD() + "\",";
                    tableData += "\"windV\":\"" + forecast.getWindV() + "\",";
                    tableData += "\"rain\":\"" + forecast.getRain() + "\",";
                    tableData += "\"humid\":\"" + forecast.getMaxhumid() + "\",";
                    tableData += "\"weatherPic1\":\"" + forecast.getWeatherPic1() + "\",";
                    tableData += "\"weatherPic2\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPhenomena\":\"" + forecast.getWeatherPhenomena() + "\",";
                    tableData += "\"strWeather1\":\"" + forecast.getStrWeather1() + "\",";
                    tableData += "\"strWeather2\":\"" + forecast.getStrWeather2() + "\",";
                    tableData += "\"week\":\"" + forecast.getWeek() + "\",";
                    tableData += "\"day\":\"" + forecast.getDay() + "\"";
                    tableData += "},";
                    tableData += "{";
                    tableData += "\"dateTime\":\"" + forecast.getDateTime() + "\",";
                    tableData += "\"maxTemp\":\"" + forecast.getMaxTemp() + "\",";
                    tableData += "\"minTemp\":\"" + forecast.getMinTemp() + "\",";
                    tableData += "\"windD\":\"" + forecast.getWindD() + "\",";
                    tableData += "\"windV\":\"" + forecast.getWindV() + "\",";
                    tableData += "\"rain\":\"" + forecast.getRain() + "\",";
                    tableData += "\"humid\":\"" + forecast.getMaxhumid() + "\",";
                    tableData += "\"weatherPic1\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPic2\":\"" + forecast.getWeatherPic2() + "\",";
                    tableData += "\"weatherPhenomena\":\"" + forecast.getWeatherPhenomena() + "\",";
                    tableData += "\"strWeather1\":\"" + forecast.getStrWeather1() + "\",";
                    tableData += "\"strWeather2\":\"" + forecast.getStrWeather2() + "\",";
                    tableData += "\"week\":\"" + forecast.getWeek() + "\",";
                    tableData += "\"day\":\"" + forecast.getDay() + "\"";
                    tableData += "},";
                }
                tableData = tableData.substring(0, tableData.length() - 1) + "]";
                xValue = xValue.substring(0, xValue.length() - 1) + "]";
                yValue = yValue.substring(0, yValue.length() - 1) + "]";
                yValue1 = yValue1.substring(0, yValue1.length() - 1) + "]";
                yValue = "[{name:'高温',color:'rgba(251,194,118,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue + "},"
                        + "{name:'低温',color:'rgba(150,205,247,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue1 + "}]";
                temp = tableData + "|" + xValue + "|" + yValue;
            } else {
                temp = "[]";
            }
        }
        return temp;
    }

    /***
     * 重要通知 查询
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetImportant_notify")
    @ResponseBody
    public Object GetImportant_notify(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        Object list = basicInfoService.GetImportant_notify(request);
        return list;
    }

    /***
     * 重点工作 查询
     * @param request
     * @param model
     * @return
     */

    @RequestMapping("/GetImportant_work")
    @ResponseBody
    public Object GetImportant_work(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetImportant_work(request);
        return list;
    }

    /* 面实体排序 */
    class SortByColor implements Comparator<Object> {
        public int compare(Object o1, Object o2) {
            // TODO Auto-generated method stub
            Entites entity1 = (Entites) o1;
            Entites entity2 = (Entites) o2;
            if (Integer.parseInt(entity1.getColor()) > Integer.parseInt(entity2.getColor()))
                return -1;
            return 1;
        }
    }

    /***
     * 得到水库面坐标信息
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/shuiKu")
    @ResponseBody
    public Object getShuiKuLike(HttpServletRequest request, Model model) {
        String reservoirname = request.getParameter("reservoirname");
        List<water_station> warning = basicInfoService.InitReservoirInfo(reservoirname);
        List<water_station> resultList = new ArrayList<water_station>();
        int count = warning.toArray().length;
        String lgtd = "";
        String lttd = "";
        String stcd = "";
        String stnm = "";
        for (int i = 0; i < count; i++) {
            lgtd = warning.get(i).getLgtd();
            lttd = warning.get(i).getLttd();
            stcd = warning.get(i).getStcd();
            stnm = warning.get(i).getStnm();
            ArrayList<Entitess> entites = new ArrayList<Entitess>();
            if (warning.get(i).getDtrange() != null) {
                String[] posArr = warning.get(i).getDtrange().split("\\*");// 三个部分，*分隔
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        Entitess entity = new Entitess();// 实体类：颜色，坐标
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                        String[] dotset = pos.split(";");// 坐标数组
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(",");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            MyPoint dm = new MyPoint(dmDot.x, dmDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        entity.setPosArr(tempPos);
                        entity.setColor("#B2FECE");
                        entites.add(entity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                water_station water_station = new water_station();
                water_station.setEntitess(entites);
                water_station.setStcd(stcd);
                water_station.setStnm(stnm);
                water_station.setLgtd(lgtd);
                water_station.setLttd(lttd);
                System.out.println(entites);
                resultList.add(water_station);
            }
        }
        return resultList;
    }

    /***
     * 得到灌溉预报等级信息
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/GetIrrigationFcstInfo")
    @ResponseBody
    public Object GetIrrigationFcstInfo(HttpServletRequest request, Model model) throws Exception {
        reservoir_irrigation_index_fcst selectKey = new reservoir_irrigation_index_fcst();// 查询类
        String strDate = request.getParameter("datechar") + " 00:00:00";// 开始时间
        String timechar = request.getParameter("timechar");// 时次
        String ntimes = request.getParameter("ntimes");  //时效
        String time = "";
        selectKey.setDatechar(strDate);
        selectKey.setTimechar(timechar);
        selectKey.setNtimes(Integer.parseInt(ntimes));
        List<reservoir_irrigation_index_fcst> resultList = new ArrayList<reservoir_irrigation_index_fcst>();// 主
        List<reservoir_irrigation_index_fcst> IrrigationFcst = basicInfoService.GetIrrigationFcstInfo(selectKey); //
        int count = IrrigationFcst.toArray().length;
        for (int i = 0; i < count; i++) {
            ArrayList<Entitess> entites = new ArrayList<Entitess>();
            time = IrrigationFcst.get(i).getDatechar().toString();

            if (IrrigationFcst.get(i).getPos() != null) {
                String[] posArr = IrrigationFcst.get(i).getPos().split("\\*");// 三个部分，*分隔
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        Entitess entity = new Entitess();// 实体类：颜色，坐标
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                        String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                        entity.setColor(strColor);// 存入类
                        String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        entity.setPosArr(tempPos);
                        entites.add(entity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                Collections.sort(entites, new SortByColor());// 排序
                reservoir_irrigation_index_fcst nwarning = new reservoir_irrigation_index_fcst();// 总
                nwarning.setDatechar(time);
                nwarning.setTimechar(timechar);
                nwarning.setNtimes(Integer.parseInt(ntimes));
                nwarning.setEntitess(entites);
                nwarning.setPos(IrrigationFcst.get(i).getPos());
                resultList.add(nwarning);
            }
        }
        return resultList;
    }

    /***
     * 得到水库灌溉等级预报文档
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getIrrigationDoc")
    @ResponseBody
    public Object getIrrigationDoc(HttpServletRequest request, Model model) throws ParseException {
        String datechar = request.getParameter("datechar");// 获取预报日期
        if (datechar == null) {
            return "[]";
        }
        String timechar = request.getParameter("timechar");// 获取预报时次
        String ntimes = request.getParameter("ntimes");// 获取预报时效
        //水库灌溉等级预报2020051820_48.doc
        String docName = "水库灌溉等级预报" + datechar.replaceAll("-", "") + timechar + "_" + ntimes + ".doc";
        String id = basicInfoService.getProductID(docName);// 获取编号
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\IrrigationFcst\\";// 临时文件目录

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docName.split("\\\\")[docName.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        String servicePath = "";// 服务器文件
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "Temp\\IrrigationFcst\\" + fileName.replace(doctype, "pdf");
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                byte[] data = mongoService.selectData(map);
                // 下载doc文件
                if (new String(data).equals("")) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                servicePath = "Temp\\IrrigationFcst\\" + fileName.replace(doctype, "pdf");
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /***
     * 获取水库入库流量预报结果信息
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/GetInboundFlowFcstInfo")
    @ResponseBody
    public Object GetInboundFlowFcstInfo(HttpServletRequest request, Model model) throws Exception {
        String reservoirname = request.getParameter("reservoirname");
        List<reservoir_water_fcst> resultList = basicInfoService.GetInboundFlowFcstMaxTime();// 最新时间
        List<reservoir_water_fcst> reservoirList = new ArrayList<>();
        if (resultList.size() > 0) {
            reservoir_water_fcst selectKey = new reservoir_water_fcst();

            reservoir_water_fcst result = resultList.get(0);
            String datechar = result.getDatechar();
            String timechar = result.getTimechar();
            String ntimes = "24";
            selectKey.setDatechar(datechar.substring(0, 10));
            selectKey.setTimechar(timechar);
            selectKey.setNtimes(ntimes);
            reservoirList = basicInfoService.GetInboundFlowFcstInfo(selectKey, reservoirname); // 获取水库入库流量预报结果信息
            List<water_station> station = basicInfoService.InitReservoirInfo(reservoirname);
            if (reservoirList.size() > 0) {
                for (int i = 0; i < reservoirList.size(); i++) {
                    String stationid = reservoirList.get(i).getStationid();
                    for (int j = 0; j < station.size(); j++) {
                        if (station.get(j).getStcd().equals(stationid)) {
                            reservoirList.get(i).setLongitude(Float.parseFloat(station.get(j).getLgtd()));
                            reservoirList.get(i).setLatitude(Float.parseFloat(station.get(j).getLttd()));
                            reservoirList.get(i).setComments(station.get(j).getComments());
                            break;
                        }
                    }
                }
            }
        }
        return reservoirList;
    }

    /***
     *得到水库入库流量预报文档
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getInputFlowDoc")
    @ResponseBody
    public Object getInputFlowDoc(HttpServletRequest request, Model model) throws ParseException {
        String datechar = request.getParameter("datechar");// 获取预报日期
        if (datechar == null) {
            return "[]";
        }
        String timechar = request.getParameter("timechar");// 获取预报时次
        //入库流量2020051708.doc
        String docName = "入库流量" + datechar.replaceAll("-", "") + timechar + ".doc";
        String id = basicInfoService.getProductID(docName);// 获取编号
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\InputFlowFcst\\";// 临时文件目录

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docName.split("\\\\")[docName.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        String servicePath = "";// 服务器文件
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "Temp\\InputFlowFcst\\" + fileName.replace(doctype, "pdf");
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                byte[] data = mongoService.selectData(map);
                // 下载doc文件
                if (new String(data).equals("")) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                servicePath = "Temp\\InputFlowFcst\\" + fileName.replace(doctype, "pdf");
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }


    /***
     * 初始化精细化预报界面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/InitFineMaxTime")
    @ResponseBody
    public Object InitFineMaxTime(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        township_forecasttemp infotemp = basicInfoService.getInitFineMaxTime();
        String timechar = "";
        String datechar = "";
        String timeTemp = "";
        // 加载列表
        if (infotemp != null) {
            timechar = infotemp.getTimechar().trim();
            datechar = new DateTime(infotemp.getDatechar()).toDateString().trim();// 将日期转换为字符串格式
            timeTemp = "{\"newDate\":\"" + datechar.trim() + "\",\"newTime\":\"" + timechar.trim() + "\"}";
        } else {
            timeTemp = "{}";
        }
        List<township_station> townshipstation = new ArrayList<township_station>();
        if ("city".equals(type)) {
            townshipstation = basicInfoService.getloadCityStation();
        } else {
            townshipstation = basicInfoService.getloadFineStation();
        }
        String stationTemp = "[";
        // 加载列表
        if (townshipstation != null) {
            List<StationInfo> listResult = new ArrayList<StationInfo>();
            for (township_station ts : townshipstation) {
                StationInfo station = new StationInfo();
                station.setStationID(ts.getStationid().trim());
                station.setStationName(ts.getStationname().trim());
                // 乡处理
                if (station.getStationName().contains("乡")) {
                    station.setStationName(
                            station.getStationName().substring(0, station.getStationName().lastIndexOf("乡") + 1));
                }
                if (station.getStationName().contains("镇")) {
                    station.setStationName(
                            station.getStationName().substring(0, station.getStationName().lastIndexOf("镇") + 1));
                }
                if (station.getStationID().equals("S4081") || station.getStationID().equals("S4004")) {
                    continue;
                }
                listResult.add(station);
            }
            for (StationInfo sta : listResult) {
                stationTemp += "{";
                stationTemp += "\"stationID\":\"" + sta.getStationID() + "\",";
                stationTemp += "\"stationName\":\"" + sta.getStationName() + "\"";
                stationTemp += "},";
            }
            stationTemp = stationTemp.substring(0, stationTemp.length() - 1) + "]";
        } else {
            stationTemp = "[]";
        }
        ArrayList<String> result = new ArrayList<String>();
        result.add(timeTemp);
        result.add(stationTemp);
        return result;
    }

    /***
     * 精细化预报查询
     * @param request
     * @param model
     * @return
     * @throws ParseException
     * @throws JsonProcessingException
     */
    @RequestMapping("/FineForecast")
    @ResponseBody
    public Object getFineForecast(HttpServletRequest request, Model model)
            throws ParseException, JsonProcessingException {
        township_forecasttemp selectKey = new township_forecasttemp();// 查询类
        String strDate = request.getParameter("date");// 时间
        if (strDate == null) {
            return "[]";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateTime dateTime = new DateTime(sdf.parse(strDate));
        String strTime = request.getParameter("sc");// 时次
        String stationID = request.getParameter("stationID");// 类型
        selectKey.setDatechar(DateTime.parseDate(strDate).toDate());
        selectKey.setTimechar(strTime);
        selectKey.setStationid(stationID);
        List<township_forecasttemp> resultList = basicInfoService.getFineForecast(selectKey);
        WebCtrlData wcd = new WebCtrlData();
        String temp = "[";
        if (resultList != null && resultList.size() > 0) {
            // "星期五", "星期六" };
            String xValue = "[";
            String yValue = "[";
            String yValue1 = "[";
            List<FineForecast> listResult = new ArrayList<FineForecast>();
            for (int i = 0; i < resultList.size(); i += 2) {
                township_forecasttemp fcst12 = resultList.get(i);
                township_forecasttemp fcst24 = resultList.get(i + 1);
                DateTime date = dateTime.AddHours(fcst24.getNtimes() - 24 + Integer.parseInt(strTime));

                SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
                String week = dateFm.format(date.toDate());

                String strDateTime = date.GetDay() + "日";
                String day = date.GetDay() + "日";

                String strWeather1 = "";
                strWeather1 = fcst12.getWeather1().toString().trim();
                String strWeather2 = "";
                strWeather2 = fcst24.getWeather1().toString().trim();


                String strRain = fcst24.getRain().toString().trim();
                String strHumid = fcst24.getHumid().toString().replace("-65535", "-").trim();
                String weatherCode1 = WebCtrlData.WeatherNameToPicPath(strWeather1);
                String weatherCode2 = WebCtrlData.WeatherNameToPicPath(strWeather2);
                String strWeatherDisp = "";
                if (strWeather1.equals(strWeather2))
                    strWeatherDisp = strWeather1;
                else
                    strWeatherDisp = strWeather1 + "</br>转" + strWeather2;


                String strImgPic1 = "<img height='32' width='32' src='../images/tqyb/weatherDay/" + weatherCode1
                        + ".gif'>";
                String strImgPic2 = "<img height='32' width='32' src='../images/tqyb/weatherNight/" + weatherCode2
                        + ".gif'>";
                if (strTime == "20") {
                    strImgPic1 = "<img height='32' width='32' src='../images/tqyb/weatherNight/" + weatherCode1 + ".gif'>";
                    strImgPic2 = "<img height='32' width='32' src='../images/tqyb/weatherDay/" + weatherCode2 + ".gif'>";
                }
                double maxTemp = fcst12.getMaxtemp() > fcst24.getMaxtemp() ? fcst12.getMaxtemp() : fcst24.getMaxtemp();
                double minTemp = fcst12.getMintemp() > fcst24.getMintemp() ? fcst24.getMintemp() : fcst12.getMintemp();
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcst12.getWindd().toString().replace("-65535", "-").trim());
                String windD24 = wcd.GetAllFx(fcst24.getWindd().toString().replace("-65535", "-").trim());
                String windV12 = wcd
                        .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcst12.getWinds())));
                String windV24 = wcd
                        .GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcst24.getWinds())));
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "</br> 转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "</br> 转" + windV24;
                }

                FineForecast f = new FineForecast();
                f.setDateTime(strDateTime);
                f.setMaxTemp(String.valueOf(maxTemp));
                f.setMinTemp(String.valueOf(minTemp));
                f.setHumid(Double.parseDouble(strHumid == "" ? "0" : strHumid));
                f.setRain(Double.parseDouble(strRain == "" ? "0" : strRain));
                f.setWindD(windD);
                f.setWindV(windV);
                f.setWeatherPhenomena(strWeatherDisp);
                f.setWeatherPic1(strImgPic1);
                f.setWeatherPic2(strImgPic2);
                f.setRemark(fcst12.getRemark());
                f.setStrWeather1(strWeather1);
                f.setStrWeather2(strWeather2);
                f.setDay(day);
                f.setWeek(week);
                listResult.add(f);
                FineForecast f2 = new FineForecast();
                f2.setWeatherPic1(strImgPic2);
                f2.setRemark(fcst24.getRemark());
                listResult.add(f2);
                xValue += "'" + strDateTime + "',";
                yValue += maxTemp + ",";
                yValue1 += minTemp + ",";
            }
            xValue = xValue.substring(0, xValue.length() - 1) + "]";
            yValue = yValue.substring(0, yValue.length() - 1) + "]";
            yValue1 = yValue1.substring(0, yValue1.length() - 1) + "]";
            yValue = "[{name:'高温',color:'rgba(251,194,118,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue + "},"
                    + "{name:'低温',color:'rgba(150,205,247,1)',type:'spline',tooltip:{valueSuffix: '°C'},data:" + yValue1 + "}]";
            temp = JsonUtil.object2Json(listResult) + "|" + xValue + "|" + yValue;
        } else {
            temp = "[]";
        }
        return temp;
    }

    /***
     * 初始化城镇预报界面 */
    @RequestMapping("/InitCityMaxTime")
    @ResponseBody
    public Object InitCityMaxTime(HttpServletRequest request, Model model) {
        String name = request.getParameter("reservoirname");//type角色名称，水利局用户以及非水利局用户
        String city = request.getParameter("city");
        if (name == null || city == null) {
            return "[]";
        }
        forecastinfotemp infotemp = basicInfoService.getInitCityMaxTime(name, city);
        String timechar = "";
        String datechar = "";
        String timeTemp = "";
        // 加载列表
        if (infotemp != null) {
            timechar = infotemp.getTimechar().trim();
            datechar = new DateTime(infotemp.getDatechar()).toDateString().trim();// 将日期转换为字符串格式
            timeTemp = "{\"newDate\":\"" + datechar.trim() + "\",\"newTime\":\"" + timechar.trim() + "\"}";
        } else {
            timeTemp = "{}";
        }
        List<township_station> townshipstation = basicInfoService.getloadCityStation();
        String stationTemp = "[";
        // 加载列表
        if (townshipstation != null) {
            List<StationInfo> listResult = new ArrayList<StationInfo>();
            for (township_station ts : townshipstation) {
                StationInfo station = new StationInfo();
                station.setStationID(ts.getStationid());
                station.setStationName(ts.getStationname());
                listResult.add(station);
            }
            for (StationInfo sta : listResult) {
                stationTemp += "{";
                stationTemp += "\"stationID\":\"" + sta.getStationID() + "\",";
                stationTemp += "\"stationName\":\"" + sta.getStationName() + "\"";
                stationTemp += "},";
            }
            stationTemp = stationTemp.substring(0, stationTemp.length() - 1) + "]";
        } else {
            stationTemp = "[]";
        }
        ArrayList<String> result = new ArrayList<String>();
        result.add(timeTemp);
        result.add(stationTemp);
        return result;
    }

    /***
     * 获取菜单
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getmenu")
    @ResponseBody
    public Object getmenu(HttpServletRequest request, Model model) {
        String reservoirid = request.getParameter("reservoirid");
        Object list = basicInfoService.GetMenu(reservoirid);
        return list;
    }

    /***
     * 获取乡镇未来24小时天气预报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getWeather")
    @ResponseBody
    public Object getWeather(HttpServletRequest request, Model model) {
        Object list = basicInfoService.getWeather();
        return list;
    }

    /***
     * 得到水利设施
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getFacilities")
    @ResponseBody
    public Object getFacilities(HttpServletRequest request, Model model) throws ParseException {
        List<water_facilities> fcstList = basicInfoService.getFacilities();
        return fcstList;
    }

    /* 得到水利灾点查询 */
    @RequestMapping("/getSLPoint")
    @ResponseBody
    public Object getSLPoint(HttpServletRequest request, Model model) throws Exception {
        String county = request.getParameter("county");
        if (StringUtil.IsNullOrEmpty(county))
            //已改
            county = DbConfig.CITY;
        List<torrent_potential_points> resultList = basicInfoService.getSLPoint(county);
        List<DPoint> rstlist = new ArrayList<>();
        for (torrent_potential_points p : resultList) {
            DPoint pnt = new DPoint();
            pnt.setPp_id(p.getPp_id());
            pnt.setPp_name(p.getPp_name());
            pnt.setLon(Double.parseDouble(p.getLon()));
            pnt.setLat(Double.parseDouble(p.getLat()));
            pnt.setDis_level(p.getDis_level());
            pnt.setDis_type(p.getDis_type());
            pnt.setDanger_level(p.getDanger_level());
            pnt.setGeo_addr(p.getGeo_addr());
            pnt.setStationName(p.getPp_name());
            pnt.setThreat_pop(p.getThreat_pop());
            pnt.setThreat_prop(p.getThreat_prop());
            rstlist.add(pnt);
        }
        return new ResultObj("查询成功", rstlist, true);
    }

    /***
     * 查询图片
     * @param request
     * @param response
     * @param model
     * @return
     * @throws ParseException
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/getQxWarn")
    @ResponseBody
    public Object getQxWarn(HttpServletRequest request, HttpServletResponse response, Model model) throws ParseException, ServletException, IOException {
        String reservoirid = request.getParameter("reservoirid");//单位ID
        String type = request.getParameter("type");//类别 气象预警qxyj、机构设置jgsz、水利设施slss
        if (reservoirid == null || type == null) {
            return "[]";
        }
        String path = getReservoirPic(request, reservoirid, type);
        return path;
    }


    /****
     * 得到图片
     * @param request
     * @param type
     * @return
     * @throws ParseException
     */
    public String getReservoirPic(HttpServletRequest request, String reservoirid, String type) throws ParseException {
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\reservoirPic\\";
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当图片达到1000张时清除
        FileUtil.ClearTempFiles(urlpath, 1000);

        String rstpath = "";
        String fileName = reservoirid.trim() + ".png";
        String servicePath = urlpath + fileName;
        File serviceFile = new File(servicePath);
        if (serviceFile.exists()) {
            rstpath = "Temp\\reservoirPic\\" + fileName;
        } else {
            // 从mongdb获取图片
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("table_id", reservoirid);
            map.put("type", type);
            map.put("collectionName", "reservoir_jpg_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            String str = new String(data);
            if (!StringUtil.IsNullOrEmpty(str)) {
                FileUtil.bytesToFile(data, servicePath);
                rstpath = "Temp\\reservoirPic\\" + fileName;
            }
        }
        return rstpath;
    }

    /***
     * 得到距离最近的站点
     * @param request
     * @param model
     * @param model
     * @return
     */
    @RequestMapping("/initLonlat")
    @ResponseBody
    public Object initLonlat(HttpServletRequest request, Model model) {
        String stationname = request.getParameter("reservoirname");
        if (stationname == null) {
            return "[]";
        }
        List<String> lonlat = new ArrayList<>();
        if (stationname.contains("水库")){
            lonlat = basicInfoService.getReservoirLonlat(stationname);
        } else if (stationname.contains("电站")) {
            lonlat = basicInfoService.getwatereleLonlat(stationname);
        }else {//湘西
            lonlat = basicInfoService.getWaterControlBureauLonlat(stationname);
        }
        return lonlat;
    }


    /***
     * 得到最近站点未来七天天气预报
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    public List<TownshipForecast> getNearStaThreeForecast(HttpServletRequest request, Model model) throws Exception {
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String time = DateTime.now().toDateString();//; "2020-05-26"// 时间
        String sc = (DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() <= 20) ? "08" : "20";// 时次
        int nTimes = 168;
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        selectKey.setTimeChar(sc);
        selectKey.setDateChar(DateTime.parseDate(time).toDate());
        selectKey.setNTimes(nTimes);
        List<TownshipForecast> fcstList = basicInfoService.getNearStaThreeForecast(selectKey, lon, lat);
        return fcstList;
    }


    /***
     * 获取QPF数据 最新十条
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetTenQPF")
    @ResponseBody
    public Object GetTenQPF(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetTenQPF(request);
        return list;
    }

    /***
     * 获取精细化预报数据 最新三天  24天
     * @param request
     * @param model
     * @return
     */
        @RequestMapping("/GetThreeDayJXH")
    @ResponseBody
    public Object GetThreeDayJXH(HttpServletRequest request, Model model) {
        Object list = basicInfoService.GetThreeDayJXH(request);
        return list;
    }


    /* 面雨量分析 */
    @RequestMapping("/getSRainfall")           //流域实况面雨量
    @ResponseBody
    public Object getSRainfall(HttpServletRequest request, Model model) throws Exception {
        String drainagearea = request.getParameter("drainagearea");
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<String> lyList = new ArrayList<String>();
        String picpath = "";
        DateTime time = DateTime.now();
        String newDate = time.toDateTimeString("yyyy-MM-dd HH");
        String datetime = newDate+":00:00";// 时间
        String[] ntimes = new String[]{"24","120","240"};
        String areatype = "1"; //0流域  1行政
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/SKRain/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\SKRain\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String datechar = time.toDateString();
        String fileName = "";
        for (String ntime : ntimes) {
            fileName = datechar + "-" + time.GetHour() + "-" + ntime + "_"+drainagearea+".jpg";
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("datetime", datetime.toString());
                //map.put("ntimes", ntime);
                //map.put("areatype", areatype);
                map.put("type", "雨量");
                map.put("collectionName", "sk_rain_jpg_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH")+":00:00";
                    map = new HashMap<String, Object>();
                    map.put("datetime", datetime);
                    //map.put("ntimes", ntime);
                    //map.put("areatype", areatype);
                    map.put("type", "雨量");
                    map.put("collectionName", "sk_rain_jpg_file");
                    map.put("advCode", DbConfig.advCode);
                    data = mongoService.selectData(map);
                    if(data == null){
                        picpath="";
                    }
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            xzList.add(picpath);
        }
        arrayList.add(xzList);//行政雨量图

        for (String ntime : ntimes) {
            SRainfallSearch selectKey = new SRainfallSearch();// 查询类
            selectKey.setStartDate(datetime);//datetime
            selectKey.setNtimes(ntime);
            selectKey.setType("0");//0 实况  1  预报
            selectKey.setAreatype("0");//0 流域  1  行政
            List<area_rain> fcstList = basicInfoService.getSumAreaRain(selectKey);
            arrayList.add(fcstList);
        }
        return new ResultObj("查询成功", arrayList, true);
    }


    /* 预报面雨量分析 */
    @RequestMapping("/getYBRainfall")
    @ResponseBody
    public Object getYBRainfall(HttpServletRequest request, Model model) throws Exception {
//        String drainagearea = request.getParameter("drainagearea");
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<String> lyList = new ArrayList<String>();
        String picpath = "";
        String datetime = "";
        DateTime time = DateTime.now();
        String newDate = time.toDateTimeString();
//        if(time.GetHour()>=8&&time.GetHour()<=20){
//            datetime = time.toDateString()+" 08:00:00";// 时间
//        }else if(time.GetHour()>20){
//            datetime = time.toDateString()+" 20:00:00";// 时间
//        } else {
//            time=   time.AddDays(-1);
//            datetime=time.toDateString()+" 20:00:00";
//        }
        datetime = time.toDateString();// 时间
//        String[] ntimes = new String[]{"24","48","72"};
        String[] ntimes = new String[]{"024","048","072"};
//        String areatype = "1"; //0流域  1行政
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/YBRain/";
        String urlPath;
        if (operatingSystem.equals("Windows")){
            urlPath = request.getSession().getServletContext().getRealPath("/") + "Temp\\YBRain\\";// 临时文件目录
        }else {
            urlPath = request.getSession().getServletContext().getRealPath("/") + "Temp/YBRain/";// 临时文件目录
        }
        FileUtil.mkDirs(urlPath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlPath, 1000);// 清除缓存
        String datechar = time.toDateString();
        String fileName = "";
        for (String ntime : ntimes) {
//            fileName = datechar + "-" + time.GetHour() + "-" + ntime + "_"+drainagearea+".jpg";
            fileName = datechar + "-" + time.GetHour() + "-" + ntime +".jpg";
            String servicePath = urlPath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
//                map.put("datetime", datetime);
                map.put("datechar", datetime);
                map.put("ntimes", ntime);
//                map.put("areatype", areatype);
                map.put("type", "降水量");
                map.put("collectionName", "yb_rain_jpg_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            xzList.add(picpath);
        }
        arrayList.add(xzList);//行政雨量图

        for (String ntime : ntimes) {
            SRainfallSearch selectKey = new SRainfallSearch();// 查询类
            if(time.GetHour()>=8&&time.GetHour()<=20){
                datetime = time.toDateString()+" 08:00:00";// 时间
            }else{
                datetime = time.toDateString()+" 20:00:00";// 时间
            }
            selectKey.setStartDate(datetime);
            selectKey.setNtimes(ntime);
            selectKey.setType("1");//0 实况  1  预报
            selectKey.setAreatype("0");//0 流域  1  行政
            List<area_rain> fcstList = basicInfoService.getSumAreaRain(selectKey);
            arrayList.add(fcstList);
        }
        return new ResultObj("查询成功", arrayList, true);
    }

    //---------------------------------农业-------------------------------------------

    /**
     * 获取气象要素信息
     *
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年8月20日
     */
    @RequestMapping("/getQxElemMoniData")
    @ResponseBody
    public Object getQxElemMoniData() throws Exception {
        System.out.println("可能出现的问题，3010行代码 getQxEleMoniData");
        String hour = basicInfoService.getSysConfig("气象要素").get(0).getParamvalue();
        if (StringUtil.IsNullOrEmpty(hour)) {
            hour = "24";
        }
        List<warn_moni_info> warnList = basicInfoService.getQxElemMoniData(Integer.parseInt(hour));
        List<SmallScaleStation> stationList = basicInfoService.getTownStaList();
        List<QxElemMoniData> resultList = new ArrayList<QxElemMoniData>();
        for (warn_moni_info moni_info : warnList) {
            for (SmallScaleStation station : stationList) {
                if (moni_info.getStationid().equals(station.getStationID())) {
                    QxElemMoniData moniData = new QxElemMoniData();
                    moniData.setId(moni_info.getId());
                    moniData.setStationid(moni_info.getStationid());
                    moniData.setLon(station.getLongitude());
                    moniData.setLat(station.getLatitude());
                    DmMapPoint dmDot = new DmMapPoint(station.getLongitude(), station.getLatitude());
                    DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x ,dmDot.y);
                    moniData.setX(ltDot.x);
                    moniData.setY(ltDot.y);
                    moniData.setMonitorvalue(moni_info.getMonitorvalue());
                    moniData.setStationName(station.getStationName());
                    moniData.setWarningtime(new DateTime(moni_info.getWarningtime()).toDateTimeString());
                    moniData.setWarningtype(moni_info.getWarningtype());
                    resultList.add(moniData);
                }

            }
        }
        // 获取预警监控信息
        return new ResultObj("可能存在的问题",resultList,true);
    }

    /***
     * 获取农业预警信号  当天
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWarnSignalInfoNy")
    @ResponseBody
    public Object GetWarnSignalInfoNy(HttpServletRequest request, Model model) {
        List<Object> rltList = new ArrayList<>();
        Object list = basicInfoService.GetWarnSignalInfo();
        rltList.add(list);
        return rltList;
    }

    /***
     * 获取农情监控信息  当天
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetNqjk")
    @ResponseBody
    public Object GetNqjk(HttpServletRequest request, Model model) {
        List<Object> List = new ArrayList<>();
        Object list = basicInfoService.getNqjk();
        List.add(list);
        return List;
    }

    /* 农业活动预报 */
    @RequestMapping("/GetRnshdyb")
    @ResponseBody
    public Object GetRnshdyb(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<agri_product> AgriList = new ArrayList<agri_product>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<agri_product> list = basicInfoService.getRnshdyb();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        for (agri_product agri : list) {
            if(agri.getProductname().contains("喷药")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "喷药" + ".png";
            }else if(agri.getProductname().contains("施肥")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "施肥" + ".png";
            }else if(agri.getProductname().contains("灌溉")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "灌溉" + ".png";
            }else{
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "收晒" + ".png";
            }
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", agri.getId());
                map.put("table_name", "agri_product");
                map.put("collectionName", "image_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            agri.setPicpath(picpath);
            AgriList.add(agri);
        }
        arrayList.add(AgriList);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 农业气象灾害区划 */
    @RequestMapping("/GetQxzhqh")
    @ResponseBody
    public Object GetQxzhqh(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<agri_product> AgriList = new ArrayList<agri_product>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<agri_product> list = basicInfoService.getQxzhqh();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_ZH/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_ZH\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        for (agri_product agri : list) {
            if(agri.getProductname().contains("五月低温")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "五月低温" + ".jpg";
            }else if(agri.getProductname().contains("干旱")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "干旱" + ".jpg";
            }else if(agri.getProductname().contains("寒露风")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "寒露风" + ".jpg";
            }else if(agri.getProductname().contains("洪涝")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "洪涝" + ".jpg";
            }else if(agri.getProductname().contains("倒春寒")){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "倒春寒" + ".jpg";
            }else {
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                        + "高温热害" + ".jpg";
            }
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", agri.getId());
                map.put("table_name", "agri_product");
                map.put("collectionName", "image_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            agri.setPicpath(picpath);
            AgriList.add(agri);
        }
        arrayList.add(AgriList);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }


    /* 月农用天气预报 */
    @RequestMapping("/GetYry")
    @ResponseBody
    public Object GetYry(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<agri_product> AgriList = new ArrayList<agri_product>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<agri_product> list = basicInfoService.getYry();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_Topic/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_Topic\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        for (agri_product agri : list) {
            fileName = agri.getProductname().replace(".doc",".pdf");
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", agri.getId());//agri.getId()
                map.put("table_name", "agri_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            agri.setPicpath(picpath);
            AgriList.add(agri);
        }
        arrayList.add(AgriList);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 产量预报 */
    @RequestMapping("/GetClyb")
    @ResponseBody
    public Object GetClyb(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<agri_product> AgriList = new ArrayList<agri_product>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<agri_product> list = basicInfoService.getClyb();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_Topic/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_Topic\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        for (agri_product agri : list) {
            fileName = agri.getProductname().replace(".doc",".pdf");
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", agri.getId());//agri.getId()
                map.put("table_name", "agri_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            agri.setPicpath(picpath);
            AgriList.add(agri);
        }
        arrayList.add(AgriList);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 发育期预报 */
    @RequestMapping("/GetFyq")
    @ResponseBody
    public Object GetFyq(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<agri_product> AgriList = new ArrayList<agri_product>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<agri_product> list = basicInfoService.getFyq();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_Topic/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_Topic\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        for (agri_product agri : list) {
            fileName = agri.getProductname().replace(".doc",".pdf");
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", agri.getId());//agri.getId()
                map.put("table_name", "agri_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            agri.setPicpath(picpath);
            AgriList.add(agri);
        }
        arrayList.add(AgriList);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 病虫害 */
    @RequestMapping("/GetBch")
    @ResponseBody
    public Object GetBch(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<agri_product> AgriList = new ArrayList<agri_product>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<agri_product> list = basicInfoService.getBch();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_Topic/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_Topic\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        for (agri_product agri : list) {
            fileName = agri.getProductname().replace(".doc",".pdf");
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", agri.getId());//agri.getId()
                map.put("table_name", "agri_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            agri.setPicpath(picpath);
            AgriList.add(agri);
        }
        arrayList.add(AgriList);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 农业气象灾害预警 */
    @RequestMapping("/GetQxzh")
    @ResponseBody
    public Object GetQxzh(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        List<String> xzList = new ArrayList<String>();
        List<agri_product> AgriList = new ArrayList<agri_product>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<agri_product> list = basicInfoService.getQxzh();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_Topic/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_Topic\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        for (agri_product agri : list) {
            fileName = agri.getProductname().replace(".doc",".pdf");
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", agri.getId());//agri.getId()
                map.put("table_name", "agri_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            agri.setPicpath(picpath);
            AgriList.add(agri);
        }
        arrayList.add(AgriList);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 实况信息_雨 */
    @RequestMapping("/GetSkRain")
    @ResponseBody
    public Object GetSkRain(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_SK/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_SK\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "雨量" + ".png";
        String servicePath = urlpath + fileName;// 服务器文件
        File serviceFile = new File(servicePath);// 服务器文件
        String datetime = time.toDateTimeString("yyyy-MM-dd HH") + ":00:00";
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "雨量");
            map.put("collectionName", "sk_rain_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "雨量");
                map.put("collectionName", "sk_rain_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 实况信息_温 */
    @RequestMapping("/GetSkTemp")
    @ResponseBody
    public Object GetSkTemp(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_SK/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_SK\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "温度" + ".png";
        String servicePath = urlpath + fileName;// 服务器文件
        File serviceFile = new File(servicePath);// 服务器文件
        String datetime = time.toDateTimeString("yyyy-MM-dd HH") + ":00:00";
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "温度");
            map.put("collectionName", "sk_temp_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "温度");
                map.put("collectionName", "sk_temp_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 实况信息_风 */
    @RequestMapping("/GetSkWind")
    @ResponseBody
    public Object GetSkWind(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_SK/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_SK\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "风速" + ".png";
        String servicePath = urlpath + fileName;// 服务器文件
        File serviceFile = new File(servicePath);// 服务器文件
        String datetime = time.toDateTimeString("yyyy-MM-dd HH") + ":00:00";
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "风速");
            map.put("collectionName", "sk_wind_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "风速");
                map.put("collectionName", "sk_wind_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 实况信息_湿 */
    @RequestMapping("/GetSkHumid")
    @ResponseBody
    public Object GetSkHumid(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_SK/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_SK\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "湿度" + ".png";
        String servicePath = urlpath + fileName;// 服务器文件
        File serviceFile = new File(servicePath);// 服务器文件
        String datetime = time.toDateTimeString("yyyy-MM-dd HH") + ":00:00";
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "湿度");
            map.put("collectionName", "sk_humid_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "湿度");
                map.put("collectionName", "sk_humid_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 实况信息_压 */
    @RequestMapping("/GetSkPress")
    @ResponseBody
    public Object GetSkPress(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_SK/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_SK\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "气压" + ".png";
        String servicePath = urlpath + fileName;// 服务器文件
        File serviceFile = new File(servicePath);// 服务器文件
        String datetime = time.toDateTimeString("yyyy-MM-dd HH") + ":00:00";
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "气压");
            map.put("collectionName", "sk_press_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "气压");
                map.put("collectionName", "sk_press_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 实况信息_总 */
    @RequestMapping("/GetSkFive")
    @ResponseBody
    public Object GetSkFive(HttpServletRequest request, Model model) throws Exception {
        ArrayList<Object> arrayList = new ArrayList<>();
        String picpath = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_SK/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_SK\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "雨量" + ".png";
        String servicePath = urlpath + fileName;// 服务器文件
        File serviceFile = new File(servicePath);// 服务器文件
        String datetime = time.toDateTimeString("yyyy-MM-dd HH") + ":00:00";
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "雨量");
            map.put("collectionName", "sk_rain_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "雨量");
                map.put("collectionName", "sk_rain_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        //------------------------2-------------------------
        fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "温度" + ".png";
        servicePath = urlpath + fileName;// 服务器文件
        serviceFile = new File(servicePath);// 服务器文件
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "温度");
            map.put("collectionName", "sk_temp_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "温度");
                map.put("collectionName", "sk_temp_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        //------------------------3-------------------------
        fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "风速" + ".png";
        servicePath = urlpath + fileName;// 服务器文件
        serviceFile = new File(servicePath);// 服务器文件
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "风速");
            map.put("collectionName", "sk_wind_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "风速");
                map.put("collectionName", "sk_wind_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        //------------------------4-------------------------
        fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "湿度" + ".png";
        servicePath = urlpath + fileName;// 服务器文件
        serviceFile = new File(servicePath);// 服务器文件
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "湿度");
            map.put("collectionName", "sk_humid_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "湿度");
                map.put("collectionName", "sk_humid_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        //------------------------5-------------------------
        fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + hour + "_"
                + "气压" + ".png";
        servicePath = urlpath + fileName;// 服务器文件
        serviceFile = new File(servicePath);// 服务器文件
        if (serviceFile.exists()) {// 把文件上传到服务器
            picpath = basePath + fileName;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "气压");
            map.put("collectionName", "sk_press_png_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = mongoService.selectData(map);
            if (data == null) {
                datetime = time.AddHours(-1).toDateTimeString("yyyy-MM-dd HH") + ":00:00";
                map = new HashMap<String, Object>();
                map.put("datechar", datetime);
                map.put("type", "气压");
                map.put("collectionName", "sk_press_png_file");
                map.put("advCode", DbConfig.advCode);
                data = mongoService.selectData(map);
                if(data==null){
                    picpath = "";
                }else{
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            } else {
                FileUtil.bytesToFile(data, servicePath);
                picpath = basePath + fileName;
            }
        }
        arrayList.add(picpath);//行政雨量图
        return new ResultObj("查询成功", arrayList, true);
    }

    /* 得到火险预警信息 */
    @RequestMapping("/getFirewarning")
    @ResponseBody
    public Object getFirewarning(HttpServletRequest request, Model model) throws Exception {
        FireSearch selectKey = new FireSearch();// 查询类
        DateTime times = DateTime.now();
        String startDate = times.AddDays(-3).toDateTimeString("yyyy-MM-dd HH") + ":00:00";// 开始时间
        String endDate = times.toDateTimeString("yyyy-MM-dd HH") + ":00:00";// 结束时间
        String type = "24";
        String time = "";
        String gradeArea3 = "";
        String gradeArea4 = "";
        String gradeArea5 = "";
        String docpath = "";
        Integer docid;
        selectKey.setStartDate(startDate);
        selectKey.setEndDate(endDate);
        selectKey.setType(type);
        List<Warning> resultList = new ArrayList<Warning>();// 主
        List<HXYJ_Warning> warning = basicInfoService.getFirewarning(selectKey); //

        int count = warning.toArray().length;
        for (int i = 0; i < count; i++) {
            if (warning.get(i).getGradeArea2() != null && !warning.get(i).getGradeArea2().equals("")) {
                warning.get(i).setWarntype("蓝色预警");
            }
            if (warning.get(i).getGradeArea3() != null && !warning.get(i).getGradeArea3().equals("")) {
                warning.get(i).setWarntype("黄色预警");
            }
            if (warning.get(i).getGradeArea4() != null && !warning.get(i).getGradeArea4().equals("")) {
                warning.get(i).setWarntype("橙色预警");
            }
            if (warning.get(i).getGradeArea5() != null && !warning.get(i).getGradeArea5().equals("")) {
                warning.get(i).setWarntype("红色预警");
            }
            ArrayList<Entites> entites = new ArrayList<Entites>();

            time = warning.get(i).getDateChar().toString();
            Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(time);
            // 格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String sDate = sdf.format(date);// 时间
            docid = warning.get(i).getDocid();
            gradeArea3 = warning.get(i).getGradeArea3();// 黄色区域
            gradeArea4 = warning.get(i).getGradeArea4();// 橙色区域
            gradeArea5 = warning.get(i).getGradeArea5();// 红色区域
            docpath = warning.get(i).getDocpath();// 文档位置
            String[] posArr = warning.get(i).getPos().split("\\*");// 三个部分，*分隔
            DmMapPoint[] dt = null;
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    Entites entity = new Entites();// 实体类：颜色，坐标
                    ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();// 临时
                    String strColor = pos.split("#")[0];// #分隔，第一个代表颜色
                    entity.setColor(strColor);// 存入类
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    int ii = 0;
                    dt = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                        MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                        tempPos.add(dm);
                        dt[index]= dmDot;
                        index++;
                        ii++;
                    }
                    entity.setPosArr(tempPos);
                    entites.add(entity);
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
            Warning nwarning = new Warning();// 总
            nwarning.setGradeArea3(gradeArea3);
            nwarning.setGradeArea4(gradeArea4);
            nwarning.setGradeArea5(gradeArea5);
            nwarning.setWarntype(warning.get(i).getWarntype());
            nwarning.setDocpath(docpath);
            nwarning.setDateChar(sDate);
            nwarning.setDocid(docid);
            nwarning.setEntites(entites);
            nwarning.setDpart(dt);
            nwarning.setPos(warning.get(i).getPos());
            resultList.add(nwarning);
        }
        return resultList;
    }

    /* 农田小气候站 */
    @RequestMapping("/GetQhz")
    @ResponseBody
    public Object GetQhz(HttpServletRequest request, Model model) throws Exception {
        List<farmland_station_img> fariList = new ArrayList<farmland_station_img>();
        String picpath = "";
        String newTime = "";
        String stid = "";
        DateTime time = DateTime.now();
        String datechar = time.toDateTimeString("yyyy-MM-dd HH:mm:ss");
        String hour = datechar.substring(11, 13);
        List<farmland_station_img> list = basicInfoService.getQhz();
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/Agri_QHZ/";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri_QHZ\\";// 临时文件目录
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = "";
        String stationname = "";
        for (farmland_station_img far : list) {
            if(far.getStationid()==430723001){
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + far.getTimechar() + "_"
                        + "城步县农科所" + ".jpg";
                stationname = "城步县农科所";
            }else{
                fileName = time.GetYear() + "_" + time.GetMonth() + "_" + time.GetDay() + "_" + far.getTimechar() + "_"
                        + "城步县城头山水稻" + ".jpg";
                stationname = "城步县城头山水稻";
            }
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                newTime = new DateTime(far.getDatechar()).toDateTimeString("yyyy-MM-dd");
                stid = Integer.toString(far.getStationid());
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("stationid", stid);
                map.put("datechar",newTime);
                map.put("timechar",far.getTimechar());
                map.put("collectionName", "farm_image");
                map.put("advCode", DbConfig.advCode);
                byte[] data = mongoService.selectData(map);
                if (data == null) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            far.setPicpath(picpath);
            far.setStationname(stationname);
            fariList.add(far);
        }
        return new ResultObj("查询成功", fariList, true);
    }

    /**
     * 查询地灾隐患点
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年7月27日
     */
    @RequestMapping("/getDisPoint")
    @ResponseBody
    public Object getDisPoint(HttpServletRequest request, Model model) {
        String disId = request.getParameter("disId");
        String disName = request.getParameter("disName");
        String county = request.getParameter("county");
        String disType = request.getParameter("disType");
        String level = request.getParameter("level");
        String disLevel = request.getParameter("disLevel");
        String population = request.getParameter("population");
        String populationTo = request.getParameter("populationTo");
        String property = request.getParameter("property");
        String propertyTo = request.getParameter("propertyTo");
        DisPointSearch disPointSearch = new DisPointSearch();
        disPointSearch.setDisId(disId);
        disPointSearch.setDisName(disName);
        disPointSearch.setCounty(county);
        disPointSearch.setDisType(disType);
        disPointSearch.setLevel(level);
        disPointSearch.setDisLevel(disLevel);

        if (!(StringUtil.IsNullOrEmpty(population) || StringUtil.IsNullOrEmpty(populationTo))) {
            disPointSearch.setPopulation(Integer.parseInt(population));
            disPointSearch.setPopulationTo(Integer.parseInt(populationTo));
        }
        if (!(StringUtil.IsNullOrEmpty(property) || StringUtil.IsNullOrEmpty(propertyTo))) {
            disPointSearch.setProperty(Integer.parseInt(property));
            disPointSearch.setPropertyTo(Integer.parseInt(propertyTo));
        }
        List<potential_points> disPoints = basicInfoService.selectDisPoint(disPointSearch);
        List<DPoint> resultList = new ArrayList<DPoint>();
        for (int i = 0; i < disPoints.toArray().length; i++) {
            Double lon = WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLon().toString()));
            Double lat = WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLat().toString()));
            DmMapPoint dt = transformService.LonLatConvertToLambert(lon, lat);
            DPoint dPoint = new DPoint();
            dPoint.setLon(lon);
            dPoint.setLat(lat);
            dPoint.setPp_id(disPoints.get(i).getPp_id());
            dPoint.setField_id(disPoints.get(i).getField_id());
            dPoint.setContact(disPoints.get(i).getContact());
            dPoint.setContact_tel(disPoints.get(i).getContact_tel());
            dPoint.setContact1(disPoints.get(i).getContact1());
            dPoint.setContact1_tel(disPoints.get(i).getContact1_tel());
            dPoint.setGeo_addr(disPoints.get(i).getGeo_addr());
            dPoint.setHappen_year(disPoints.get(i).getHappen_year());
            dPoint.setHappen_month(disPoints.get(i).getHappen_month());
            dPoint.setHappen_day(disPoints.get(i).getHappen_day());
            dPoint.setDeath_toll(disPoints.get(i).getDeath_toll());
            dPoint.setDirect_loss(disPoints.get(i).getDirect_loss());
            dPoint.setCur_state(disPoints.get(i).getCur_state());
            dPoint.setStationName(disPoints.get(i).getPp_name());
            dPoint.setPp_name(disPoints.get(i).getPp_name());
            dPoint.setDis_scale(disPoints.get(i).getDis_scale());
            dPoint.setDis_type(disPoints.get(i).getDis_type());
            dPoint.setDis_level(disPoints.get(i).getDis_level());
            dPoint.setDanger_level(disPoints.get(i).getDanger_level());
            dPoint.setAttention_level(disPoints.get(i).getAttention_level());
            dPoint.setEasyissue_level(disPoints.get(i).getEasyissue_level());
            dPoint.setThreat_pop(disPoints.get(i).getThreat_pop());
            dPoint.setThreat_prop(disPoints.get(i).getThreat_prop());
            resultList.add(dPoint);
        }
        return resultList;
    }

    /***
     * 农业大户查询
     */
    @RequestMapping("/GetDhuser")
    @ResponseBody
    public Object GetDhuser() {
        Object List = basicInfoService.getDhuser();
        return List;
    }

    /**
     * 获取地灾预警信息
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年7月10日
     */
    @RequestMapping("/getDZInfo")
    @ResponseBody
    public Object getDZInfo(HttpServletRequest request, Model model) throws Exception {
        DateTime time = DateTime.now();
        String startDate = time.AddDays(-7).toDateTimeString("yyyy-MM-dd")+ " 00:00:00";
        String endDate = time.toDateTimeString("yyyy-MM-dd")+ " 23:59:59";
        String type = "短临预警";
        DZQuery dzQuery = new DZQuery();
        dzQuery.setStartDate(startDate);
        dzQuery.setEndDate(endDate);
        dzQuery.setType(type);
        List<DZWarning> result = basicInfoService.getDZInfo(dzQuery);
        // 兰伯特转经纬度
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }

            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        // 16进制颜色
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }

            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
            // 文件处理
        }
        return result;
    }

    /***
     * 获取JPG
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetJPG")
    @ResponseBody
    public Object GetJPG(HttpServletRequest request, Model model, String typeTime, String rainType) {
        if (rainType == null) {
            return "[]";
        }
        Object list = basicInfoService.GetJPG(request,typeTime,rainType);
        return list;
    }

    /***
     * 获取降水预报表
     * @param station 站名
     * @param timeType 时间类型  township_forecasttemp
     * @return
     */
    @RequestMapping("/getPrecipitationForecast")
    @ResponseBody
    public Object getPrecipitationForecast(String station,String timeType) {
        List<Rainforecast> list = basicInfoService.getPrecipitationForecast(station, timeType);
        //对集合进行排序（升序）
        Collections.sort(list, new Comparator<Rainforecast>() {
            @Override
            public int compare(Rainforecast o1, Rainforecast o2) {
                if (Integer.parseInt(o1.getDatechar())>Integer.parseInt(o2.getDatechar())){
                    return 1;
                }
                if (Integer.parseInt(o1.getDatechar())==Integer.parseInt(o2.getDatechar())){
                    return 0;
                }
                return -1;
            }
        });

        if (list.size()!=0){
            List<Map> result=new ArrayList<>();
            double leiji=0;
            for (Rainforecast rain:list) {
                Map<String,Object> map=new HashMap<>();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = df.format(rain.getDatetime().getTime()+Integer.parseInt(rain.getDatechar())*60*1000);
                leiji=leiji+Double.parseDouble(rain.getRainval());
                map.put("时间",format);
                map.put("雨量值",rain.getRainval());
                map.put("累计雨量值",leiji);
                result.add(map);
            }
            return new ResultObj("获取成功",result,true);
        }
        return new ResultObj("获取成功",null,false);
    }


    /***
     * 获取面雨量图表
     * @param type
     * @param areaType
     * @return
     */
    @RequestMapping("/getAreaRainfallChart")
    @ResponseBody
    public Object getAreaRainfallChart(String type,String areaType) {
        List<AreaRain> list = basicInfoService.getAreaRainfallChart(type, areaType);
        //对集合进行排序（升序）
        Collections.sort(list, new Comparator<AreaRain>() {
            @Override
            public int compare(AreaRain o1, AreaRain o2) {
                if (o1.getNtimes()>o2.getNtimes()){
                    return 1;
                }
                if (o1.getNtimes()==o2.getNtimes()){
                    return 0;
                }
                return -1;
            }
        });

        if (list.size()!=0){
            List<Map> result=new ArrayList<>();
            double leiji=0;
            for (AreaRain rain:list) {
                Map<String,Object> map=new HashMap<>();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = df.format(rain.getObservtime().getTime()+rain.getNtimes()*60*1000);
                leiji=leiji+Double.parseDouble(rain.getRain());
                map.put("时间",format);
                map.put("雨量值",rain.getRain());
                map.put("累计雨量值",leiji);
                result.add(map);
            }
            return new ResultObj("获取成功",result,true);
        }
        return new ResultObj("获取成功",null,false);
    }

    /***
     * 获取面雨情表
     * @param drainagearea 水利
     * @param lastday  过去时间（天）
     * @return
     */
    @RequestMapping("/getRainyWeatherTable")
    @ResponseBody
    public Object getRainyWeatherTable(String drainagearea,Integer lastday) {
        if(StringUtil.IsNullOrEmpty(drainagearea)){
            return new ResultObj("参数为空，获取失败",null,false);
        }
        List<msgmediumsmallscale> list = basicInfoService.getRainyWeatherTable(drainagearea, lastday);
        if (list.size()!=0){
            List<Map> result=new ArrayList<>();
            double leiji=0;
            for (msgmediumsmallscale msgmediumsmallscale:list) {
                Map<String,Object> map=new HashMap<>();
                leiji=leiji+msgmediumsmallscale.getRain();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = df.format(msgmediumsmallscale.getObservtime().getTime());
                map.put("时间",format);
                map.put("雨量值",msgmediumsmallscale.getRain());
                map.put("累计雨量值",leiji);
                result.add(map);
            }
            return new ResultObj("获取成功",result,true);
        }
        return new ResultObj("获取成功",null,false);
    }
}